@
import http.server
from http.server import SimpleHTTPRequestHandler
from http.server import HTTPServer
PORT = 8000
class VisibleHTTPRequestHandler(SimpleHTTPRequestHandler):
def log_request(self, cod='-', size='-'):
print(self._heading("HTTP Request"))
print(self.raw_requestline,)
for header, value in self.headers.items():
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):
return ''.join(str(self.contents))
if __name__ == '__main__':
httpd = HTTPServer(('localhost', PORT), VisibleHTTPRequestHandler)
httpd.serve_forever()
c:\Python34>.\python.exe code\VisibleWebServer.py
hello.html代码如下:
<html>
<body>Hello, world!</body>
</html>
然后通过浏览器访问:
http://localhost:8000/hello.html
============
HTTP Request
============
b'GET /hello.html HTTP/1.1\r\n'
Host: localhost:8000
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/
35.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://localhost:8000/
Cookie: Hm_lvt_f5127c6793d40d199f68042b8a63e725=1422611902; Hm_lpvt_f5127c6793d4
0d199f68042b8a63e725=1422932305
Connection: keep-alive
=============
HTTP Response
=============
[b'HTTP/1.0 200 OK\r\nServer: SimpleHTTP/0.6 Python/3.4.1\r\nDate: Tue, 03 Feb 2
015 03:28:41 GMT\r\nContent-type: text/html\r\nContent-Length: 45\r\nLast-Modifi
ed: Tue, 03 Feb 2015 02:14:36 GMT\r\n\r\n', b'<html>\r\n <body>Hello, world!</b
ody>\r\n</html>']