Python http handler

I need something like BaseHTTPRequestHandler , except that I do not want it to communicate with any sockets; I want to process raw HTTP data on my own. Is there a good way I can do this in Python?

To clarify, I need a class that receives raw TCP data from Python (NOT a socket), processes it and returns TCP data as a response (in python again). Thus, this class will handle TCP communication and will have methods that override what I send via HTTP GET and POST, for example do_GET and do_POST . So, I want something like a server infrastructure that already exists, except that I want to pass all the raw TCP packets to python, and not through the operating system sockets.

+4
source share
1 answer

BaseHTTPRequestHandler comes from StreamRequestHandler , which basically reads from self.rfile and writes to self.wfile , so you can get a class from BaseHTTPRequestHandler and provide your own rfile and wfile, for example.

 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) 

Output:

 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> 
+4
source

All Articles