Reputation: 1631
I want something like BaseHTTPRequestHandler
, except that I don't want it to bind to any sockets; I want to handle the raw HTTP data to and from it myself. Is there a good way that I can do this in Python?
To Clarify, I want a class that receives raw TCP data from Python (NOT a socket), processes it and returns TCP data as a response (to python again). So this class will handle TCP handshaking, and will have methods that override what I send on HTTP GET and POST, like do_GET
and do_POST
. So, I want something like the Server infrastructure that already exists, except I want to pass all raw TCP packets in python and not through operating system sockets.
Upvotes: 5
Views: 12388
Reputation: 88727
BaseHTTPRequestHandler
derives from StreamRequestHandler
, which basically reads from file self.rfile
and writes to self.wfile
, so you can derive a class from BaseHTTPRequestHandler
and supply your own rfile and wfile e.g.
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>
Upvotes: 3