python http手

2024-05-19 06:48:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要像^{}这样的东西,只是我不希望它绑定到任何套接字;我想自己处理与它之间的原始HTTP数据。在Python中有什么好的方法可以做到这一点吗?

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


Tags: 数据方法服务器http内容get基础设施socket
1条回答
网友
1楼 · 发布于 2024-05-19 06:48:27

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>

相关问题 更多 >

    热门问题