利用python寫了一小段代碼,裏面使用到了Python標準庫的BaseHTTPServer
來構建一個基礎HTTP服務器:html
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()
運行時拋出錯誤:python
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'
緣由:web
http.server only exists in Python 3. In Python 2, you should use the BaseHTTPServer module:ubuntu
也就是說在Python3中應該使用http.server 來代替Python2的BaseHTTPServer。服務器
(完)code