【问题标题】:python http handlerpython http处理程序
【发布时间】:2009-12-15 12:22:10
【问题描述】:

我想要BaseHTTPRequestHandler 之类的东西,但我不希望它绑定到任何套接字;我想自己处理传入和传出的原始 HTTP 数据。有没有一种好方法可以在 Python 中做到这一点?

为了澄清,我想要一个从 Python(不是套接字)接收原始 TCP 数据的类,处理它并返回 TCP 数据作为响应(再次返回给 python)。所以这个类将处理 TCP 握手,并且有一些方法可以覆盖我在 HTTP GET 和 POST 上发送的内容,比如do_GETdo_POST。所以,我想要已经存在的服务器基础设施之类的东西,除了我想在 python 中传递 所有原始 TCP 数据包,而不是通过操作系统套接字。

【问题讨论】:

    标签: python http request handler


    【解决方案1】:

    BaseHTTPRequestHandler 派生自StreamRequestHandler,它基本上从文件self.rfile 读取并写入self.wfile,因此您可以从BaseHTTPRequestHandler 派生一个类并提供您自己的rfile 和wfile,例如

    import StringIO
    from  BaseHTTPServer import BaseHTTPRequestHandler
    
    class MyHandler(BaseHTTPRequestHandler):
    
        def __init__(self, inText, outFile):
            self.rfile = StringIO.StringIO(inText)
            self.wfile = outFile
            BaseHTTPRequestHandler.__init__(self, "", "", "")
    
        def setup(self):
            pass
    
        def handle(self):
            BaseHTTPRequestHandler.handle(self)
    
        def finish(self):
            BaseHTTPRequestHandler.finish(self)
    
        def address_string(self):
            return "dummy_server"
    
        def do_GET(self):
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.end_headers()
            self.wfile.write("<html><head><title>WoW</title></head>")
            self.wfile.write("<body><p>This is a Total Wowness</p>")
            self.wfile.write("</body></html>")
    
    outFile = StringIO.StringIO()
    
    handler = MyHandler("GET /wow HTTP/1.1", outFile)
    print ''.join(outFile.buflist)
    

    输出:

    dummy_server - - [15/Dec/2009 19:22:24] "GET /wow HTTP/1.1" 200 -
    HTTP/1.0 200 OK
    Server: BaseHTTP/0.3 Python/2.5.1
    Date: Tue, 15 Dec 2009 13:52:24 GMT
    Content-type: text/html
    
    <html><head><title>WoW</title></head><body><p>This is a Total Wowness</p></body></html>
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多