#!/usr/bin/env python 3.4import http.serverfrom http.server import HTTPServerfrom http.server import BaseHTTPRequestHandlerdef run(server_class = HTTPServer, handler_class = BaseHTTPRequestHandler): server_address = ('',8000)#設置端口 httpd = server_class(server_address, handler_class) httpd.serve_forever()if __name__ == '__main__': run()再看一個復雜一點的服務端,打印出接受的請求以及發回去的內容:#!/usr/bin/env python 3.4import http.serverfrom http.server import SimpleHTTPRequestHandlerfrom http.server import HTTPServerPORT = 8000 #端口號class VisibleHTTPRequestHandler(SimpleHTTPRequestHandler): def log_request(self, code='-', size='-'): "在do_GET的時候調用到" print(self._heading("HTTP Request")) print(self.raw_requestline,) for header, value in self.headers.items():#http頭的內容 print(header + ":", value) def do_GET(self, method='GET'): self.wfile = FileWrapper(self.wfile) SimpleHTTPRequestHandler.do_GET(self)#處理客戶端的請求 print("") print(self._heading("HTTP Response")) print(self.wfile)#將內容打印出來 def _heading(self, s): line = '=' * len(s) return line + '/n' + s + '/n' + line#對文件進行一層封裝class FileWrapper: def __init__(self, wfile): self.wfile = wfile self.contents = [] def __getattr__(self, key): return getattr(self.wfile, key) def write(self, s): self.contents.append(s) self.wfile.write(s) def __str__(self): print(self.contents) return ''.join(str(s) for s in self.contents)if __name__ == '__main__': httpd = HTTPServer(('localhost', PORT), VisibleHTTPRequestHandler) httpd.serve_forever()看一看打印的日志,============HTTP Request============b'GET /index.html HTTP/1.1/r/n' #這是一條命令。GET是動詞,資源標識符是/index.html,http版本號:HTTP/1.1#下面是一系列頭的鍵值對,提供了關于請求的額外信息Host: localhost:8000 #目標主機的地址和端口Connection: keep-alive #鏈接的方式,持久鏈接Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8#客戶端希望接受的數據類型Upgrade-Insecure-Requests: 1 #讓瀏覽器自動從http升級到https。User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.22 Safari/537.36 SE 2.X MetaSr 1.0#包含了操作系統版本,CPU類型,瀏覽器版本等信息Accept-Encoding: gzip, deflate, sdch #表明瀏覽器有能力解碼的編碼類型Accept-Language: zh-CN,zh;q=0.8 #表示瀏覽器所支持的語言類型=============HTTP Response=============b'HTTP/1.0 200 OK/r/n #響應狀態Server: SimpleHTTP/0.6 Python/3.4.0/r/n #服務器版本Date: Mon, 06 Mar 2017 04:06:04 GMT/r/n #日期Content-type: text/html/r/n #文件類型Content-Length: 137/r/n #文件長度Last-Modified: Thu, 02 Mar 2017 07:33:15 GMT/r/n/r/n'b'#最后更改日期#<!DOCTYPE HTML>/r/n<html>/r/n<body>/r/n<h1> fable /xb3/xcc/xd0/xf2/xd4/xb1 http://blog.csdn.net/u012175089</h1>/r/nxxxxxxxxx fable xxxxxxxxxx/r/n/r/n</body>/r/n</html>/r/n'
新聞熱點
疑難解答