利用python写了一小段代码,里面使用到了Python标准库的BaseHTTPServer
来构建一个基础HTTP服务器:
1 #-*- coding:utf-8 -*-
2 import http.server
3
4 class RequestHandler(http.server.BaseHTTPRequestHandler):
5
6 Page = '''\
7 <html>
8 <body>
9 <p> Hello,web!</p>
10 </body>
11 </html>
12 '''
13
14 #处理一个请求
15 def do_GET(self):
16 self.send_response(200)
17 self.send_header("Content-Type","text/html")
18 self.send_header("Content-Length",str(len(self.Page)))
19 self.end_headers()
20 self.wfile.write(self.Page)
21
22 if __name__ == '__main__':
23 serverAddress = ('', 8080)
24 server = http.server.HTTPServer(serverAddress, RequestHandler)
25 server.serve_forever()
运行时抛出错误:
ortonwu@ubuntu:~/data/web-server$ python server.py
Traceback (most recent call last):
File "server.py", line 2, in <module>
import BaseHTTPServer
ImportError: No module named 'BaseHTTPServer'
原因:
http.server only exists in Python 3. In Python 2, you should use the BaseHTTPServer module:
也就是说在Python3中应该使用http.server 来代替Python2的BaseHTTPServer。
(完)