3

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?

tshepang
  • 12,111
  • 21
  • 91
  • 136
BloonsTowerDefence
  • 1,184
  • 2
  • 18
  • 43

1 Answers1

4

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.

nmikhailov
  • 1,413
  • 14
  • 24
  • ok thanks its working, but is printing twice. I've looking deep into the code but can't find why? (Its not that big of a deal, just curious) – BloonsTowerDefence Feb 20 '13 at 17:32
  • Actually It may have something to do with my .Js – BloonsTowerDefence Feb 20 '13 at 17:32
  • If you are getting this output per connection: `Client requested: GET / ` ` localhost.localdomain - - [21/Feb/2013 00:38:24] "GET / HTTP/1.1" 200 - ` ` Client requested: GET / localhost.localdomain - - [21/Feb/2013 00:38:24] "GET / HTTP/1.1" 200 - ` then there is probably something with your js. Or you just dont want this `localhost.localdomain - - [21/Feb/2013 00:38:24] "GET / HTTP/1.1" 200 -` to be printed? – nmikhailov Feb 20 '13 at 17:42
  • is there a way to check if it is succesful from my handler script? i.e. check if the response is 200 ? – BloonsTowerDefence Feb 20 '13 at 20:12
  • 1
    Try overriding `send_response` instead of do_GET: class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def send_response(self, code, message=None): SimpleHTTPServer.SimpleHTTPRequestHandler.send_response(self, code, message) print "Client requested:", self.command, self.path print "Code:", code – nmikhailov Feb 21 '13 at 02:56