How to build a simple HTTP POST server?

Go To StackoverFlow.com

1

class MyHandler( BaseHTTPServer.BaseHTTPRequestHandler):
    def do_POST( self ):
        ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
        postvars = {}
        try:
          if ctype == 'application/x-www-form-urlencoded':
              length = int(self.headers.getheader('content-length'))
              postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)

          self.send_response( 200 )
          self.send_header( "Content-type", "text")
          self.send_header( "Content-length", str(len(body)) )
          self.end_headers()
          self.wfile.write(body)
        except:
          print "Error"


def httpd(handler_class=MyHandler, server_address = ('2.3.4.5', 80)):
    try:
        print "Server started"
        srvr = BaseHTTPServer.HTTPServer(server_address, handler_class)
        srvr.serve_forever() # serve_forever
    except KeyboardInterrupt:
        server.socket.close()


if __name__ == "__main__":
    httpd( )

I have most of the code ready. I need to add code for closing the connection if the client is inactive or does not respond for say 10 seconds (something like https://stackoverflow.com/a/265741/204623). Basically I don't want the server to not block on the call to send_response(), wfile.write() etc. How can I do this?

2012-04-04 19:21
by Bruce
Im not sure why you want to build this but if it is not going to receive a lot of hits, does not need to do anything other that POST and/or GET, and you dont mind being public, you can use Google App Engine, which is easy to set up - apple16 2012-04-04 22:05


3

Try this:

import BaseHTTPServer

class TimeoutServer(BaseHTTPServer.HTTPServer):
    def get_request(self):
        result = self.socket.accept()
        result[0].settimeout(10)
        return result

Then use the TimeoutServer class in place of HTTPServer to get timeout support.

2012-04-30 05:10
by javawizard
Ads