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?
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.