views:

239

answers:

1

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

+2  A: 

Look into THE code, 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</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</head><body><p>This is a Total Wowness</p></body></html>
Anurag Uniyal
Thanks for this. However, I really want to give it RAW TCP data, and get the raw TCP data response back.
Alex
why don't you write your own tcp server, twisted(http://twistedmatrix.com/) might help or may be answer to this http://stackoverflow.com/questions/1581087/python-tcp-stack-implementation
Anurag Uniyal
also see http://www.secdev.org/projects/scapy/doc/introduction.html?highlight=syn
Anurag Uniyal