HTTP 服务器
1. 前言
Python中有很多知名的Web服务器框架,比如:Django
、Flask
等。
本章的重点不在于介绍这些框架,而是从更底层的角度,使用Python自带的BaseHTTPServer
库,来实现一个简单的HTTP服务器。这个库在Python3中改成了http.server
,可以使用以下代码进行兼容:
try:
import BaseHTTPServer as httpserver
except ImportError:
import http.server as httpserver
2. 创建HTTP请求处理器
与处理TCP请求类似,处理HTTP请求也需要实现一个继承自BaseHTTPRequestHandler
处理器。
下面实现了一个访问本地文件的HTTP服务器:
class HTTPFileRequestHandler(httpserver.BaseHTTPRequestHandler):
'''文件访问处理器
'''
def do_GET(self):
'''handle GET request
'''
path = self.path
pos = self.path.find('?')
if pos > 0 :
path = self.path[:pos]
if path == '/':
path = path[1:] # remove first /
path = os.path.join(os.getcwd(), path.replace('/', os.sep))
print path
if not os.path.exists(path):
self.send_error(404)
return
ext = os.path.splitext(path)[-1].lower()[1:]
if ext in ('jpg', 'jpeg'):
content_type = 'image/jpeg'
elif ext == 'png':
content_type = 'image/png'
elif ext == 'gif':
content_type = 'image/gif'
elif ext == 'js':
content_type = 'application/javascript'
elif ext == 'css':
content_type = 'text/css; charset=utf-8'
elif ext == 'html':
content_type = 'text/html; charset=UTF-8'
else:
content_type = 'application/octet-stream'
with open(path, 'rb') as fp:
content = fp.read()
self.send_response(200)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", len(content))
self.end_headers()
self.wfile.write(content)
3. 启动HTTP服务器
httpd = httpserver.HTTPServer(('127.0.0.1', 8080), HTTPFileRequestHandler)
httpd.serve_forever()
这样就实现了一个简单的文件服务器。
事实上,Python系统库中已经实现了这样的功能。使用以下代码可以启动这个HTTP服务器:
$ python2 -m SimpleHTTPServer
或者
python3 -m http.server
将它用作临时的HTTP文件服务器还是不错的。