Python web sever 代码

@

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>']



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值