用Python编写一个简单的Http Server

Python内置了支持HTTP协议的模块,我们可以用来开发单机版功能较少的Web服务器。Python支持该功能的实现模块是BaseFTTPServer, 我们只需要在项目中引入就可以了:

from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
  • 1

Hello world !

Let’s start with the first basic example. It just return “Hello World !” on the web browser.
让我们来看第一个基本例子,在浏览器上输出”Hello World ”
example1.py

#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer PORT_NUMBER = 8080 #This class will handles any incoming request from
#the browser
class myHandler(BaseHTTPRequestHandler): #Handler for the GET requests
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
# Send the html message
self.wfile.write("Hello World !")
return try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER #Wait forever for incoming htto requests
server.serve_forever() except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

执行以下命令运行:

python example1.py

用你的浏览器打开这个地址http://your_ip:8080
浏览器上将会显示”Hello World !” 同时在终端上将会出现两条日志信息:

Started httpserver on port 8080
10.55.98.7 - - [30/Jan/2012 15:40:52] “GET / HTTP/1.1” 200 -
10.55.98.7 - - [30/Jan/2012 15:40:52] “GET /favicon.ico HTTP/1.1” 200 -

Serve static files

让我们来尝试下提供静态文件的例子,像index.html, style.css, javascript和images:

example2.py

#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep PORT_NUMBER = 8080 #This class will handles any incoming request from
#the browser
class myHandler(BaseHTTPRequestHandler): #Handler for the GET requests
def do_GET(self):
if self.path=="/":
self.path="/index_example2.html" try:
#Check the file extension required and
#set the right mime type sendReply = False
if self.path.endswith(".html"):
mimetype='text/html'
sendReply = True
if self.path.endswith(".jpg"):
mimetype='image/jpg'
sendReply = True
if self.path.endswith(".gif"):
mimetype='image/gif'
sendReply = True
if self.path.endswith(".js"):
mimetype='application/javascript'
sendReply = True
if self.path.endswith(".css"):
mimetype='text/css'
sendReply = True if sendReply == True:
#Open the static file requested and send it
f = open(curdir + sep + self.path)
self.send_response(200)
self.send_header('Content-type',mimetype)
self.end_headers()
self.wfile.write(f.read())
f.close()
return except IOError:
self.send_error(404,'File Not Found: %s' % self.path) try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER #Wait forever for incoming htto requests
server.serve_forever() except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62

这个新样例实现功能:

  • 检查请求文件扩展名
  • 设置正确的媒体类型返回给浏览器
  • 打开请求的文件
  • 发送给浏览器

输入如下命令运行它:

python example2.py

然后用你的浏览器打开 http://your_ip:8080
一个首页会出现在你的浏览器上

Read data from a form

现在探索下如何从html表格中读取数据

example3.py

#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep
import cgi PORT_NUMBER = 8080 #This class will handles any incoming request from
#the browser
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
if self.path=="/":
self.path="/index_example3.html" try:
#Check the file extension required and
#set the right mime type sendReply = False
if self.path.endswith(".html"):
mimetype='text/html'
sendReply = True
if self.path.endswith(".jpg"):
mimetype='image/jpg'
sendReply = True
if self.path.endswith(".gif"):
mimetype='image/gif'
sendReply = True
if self.path.endswith(".js"):
mimetype='application/javascript'
sendReply = True
if self.path.endswith(".css"):
mimetype='text/css'
sendReply = True if sendReply == True:
#Open the static file requested and send it
f = open(curdir + sep + self.path)
self.send_response(200)
self.send_header('Content-type',mimetype)
self.end_headers()
self.wfile.write(f.read())
f.close()
return except IOError:
self.send_error(404,'File Not Found: %s' % self.path) #Handler for the POST requests
def do_POST(self):
if self.path=="/send":
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
}) print "Your name is: %s" % form["your_name"].value
self.send_response(200)
self.end_headers()
self.wfile.write("Thanks %s !" % form["your_name"].value)
return try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER #Wait forever for incoming htto requests
server.serve_forever() except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78

运行这个例子:

python example3.py

在 “Your name” 标签旁边输入你的名字

最新文章

  1. isKindOfClass和isMemberOfClass 区别
  2. Centos6 服务器病毒查杀命令历史
  3. CSS3打造3D效果——perspective transform的深度剖析
  4. POJ-2886 Who Gets the Most Candies?(线段树+模拟)
  5. HDU 5019 Revenge of GCD(数学)
  6. android开发,assets下面的资源文件不会变化/改动
  7. 利用Eclipse的JPA自动生成注解实体
  8. 3、debian8安装和处理
  9. inux_异常_07_ftp查看不到文件列表
  10. Python--基础二
  11. JAVA关键字及作用
  12. 【XSY2760】nonintersect 计算几何
  13. Node.js中文乱码解决方法
  14. Luogu3164 CQOI2014 和谐矩阵 异或高斯消元
  15. python中类的概念
  16. 移动端开发在iOS系统中 new Date() 返回 NaN 的问题
  17. SpringBoot日记——信息修改PUT篇
  18. SpringBoot Mybatis 执行自定义SQL
  19. win10家庭版没有组策略怎么办?(win10管理员已阻止你运行此应用”解决方法)
  20. Shell脚本 数据清洗

热门文章

  1. OSPF的特征、术语、包类型、邻居关系的建立、RID的选择、DR和BDR的选举、度量值的计算、默认路由、验证
  2. 用python做数字油画或者从一幅画学习风格,去画另一幅画
  3. 基于jquery的ui选择之路
  4. 【转】Graphics.DrawCurve的算法
  5. JsonCpp 判断 value 中是否有某个KEY
  6. CI框架 -- URI 路由
  7. [SQL Server] 复制数据库任务
  8. MySQL错误ERROR 2002 (HY000): Can't connect to local MySQL server
  9. memcached能获取所有的key吗
  10. 管道符和作业控制 shell变量 环境变量配置文件