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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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)
Actually It may have something to do with my .Js
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?
is there a way to check if it is succesful from my handler script? i.e. check if the response is 200 ?
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.