How to implement Timeout in BaseHTTPServer.BaseHTTPRequestHandler Python

Tara Singh picture Tara Singh · Dec 12, 2010 · Viewed 11.7k times · Source

In my python script, I am trying to run a web server:

server = BaseHTTPServer.HTTPServer(('127.0.0.1',8080), RequestHandler)

I have a request handler class:

class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(self):
        # Doing Some Stuff.

Now I always wait for some data to catch in do_GET. I want to implement a timeout operation where I want this web server to close after lets say 60 seconds. I am not able to implement that. Please suggest me how can I implement auto shut down operation for web server in this scenario.

Thanks Tara Singh

Answer

SimonJ picture SimonJ · Dec 12, 2010

Assuming I've understood your question correctly, you can't implement a read timeout in do_GET since the request has already been read by the time this method is called.

Since BaseHTTPRequestHandler extends StreamRequestHandler which in turn extends BaseRequestHandler, you can override setup() to initialise the socket with a timeout:

class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  def setup(self):
    BaseHTTPServer.BaseHTTPRequestHandler.setup(self)
    self.request.settimeout(60)

  def do_GET(self):
    # ...