#!/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'
新闻热点
疑难解答