Python HTTP 处理器

5 投票
1 回答
11949 浏览
提问于 2025-04-15 17:02

我想要一个类似于BaseHTTPRequestHandler的东西,不过我不想让它绑定到任何网络接口上;我想自己处理进出的原始HTTP数据。有没有好的方法可以在Python中做到这一点?

为了更清楚,我想要一个类,它可以接收来自Python的原始TCP数据(不是通过网络接口),处理这些数据,然后返回TCP数据作为响应(再次返回给Python)。所以这个类会处理TCP的握手,并且会有一些方法来覆盖我在HTTP GET和POST请求中发送的内容,比如do_GETdo_POST。总之,我想要一个已经存在的服务器架构,只不过我希望能够直接在Python中处理所有原始的TCP数据包,而不是通过操作系统的网络接口。

1 个回答

3

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>

撰写回答