Search code examples
pythonpython-2.7socketserversimplehttpserver

SimpleHTTPServer and SocketServer


I have created a 'handler' python script as follows:

import SimpleHTTPServer
import SocketServer

PORT = 8000
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "Serving at port:", PORT
httpd.serve_forever()

I also have a javascript function, which sends information to the server a URL request. This all works fine, when I run my handler script, and then my javascript, I can see all of the data from the JS in the terminal:

localhost.localadmin - - [20/Feb/2013] "GET /?var=data/ HTTP/1.1" 200 -

What I would like to do, is be able to access this data from my handler script, ideally somethig like this:

data = httpd.server_forever()  #How do I do somethign like this

How do I accomplish such a thing?


Solution

  • You can inherit SimpleHTTPServer.SimpleHTTPRequestHandler like this:

    class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
      def do_GET(self):
          # Your code here
          print "Client requested:", self.command, self.path
    
          SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
    
    PORT = 8000
    
    httpd = SocketServer.TCPServer(("", PORT), MyHandler)
    
    print "Serving at port:", PORT
    httpd.serve_forever()
    

    That will print in console:

    Client requested GET /?var=data/
    

    Check documentation on SimpleHTTPRequestHandler and BaseHTTPRequestHandler for more information.