Search code examples
pythontimeoutbasehttpserver

Python - BaseHTTPServer - Overriding "handle_timeout" method


I'm currently working with Python's BaseHTTPServer and I need to override the handle_timeout() method of the server.

According to Python's documentation (https://docs.python.org/2/library/basehttpserver.html), BaseHTTPServer is a subclass of TCPServer. TCPServer implements the method handle_timeout (https://docs.python.org/2/library/socketserver.html#SocketServer.BaseServer.handle_timeout) which I want to override.

My code looks currently like this:

class newServer(BaseHTTPServer.HTTPServer):

def handle_timeout(self):
    print "Timeout!"

class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):

def setup(self):
    self.timeout=2
    BaseHTTPServer.BaseHTTPRequestHandler.setup(self)  


if __name__ == '__main__':

server=newServer

httpd = server((HOST_NAME, PORT_NUMBER), RequestHandler)
print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
try:
    httpd.serve_forever()
except KeyboardInterrupt:
    pass


httpd.server_close()
print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)

The timeout itself works, I receive the following message from the server:

Request timed out: timeout('timed out',)

The problem is, that this is not the message I want to print. Any help with my problem?


Solution

  • For anyone interested, after trying a few things out I finally came to a conclusion:

    According to this file (https://svn.python.org/projects/python/trunk/Lib/BaseHTTPServer.py), I directly copied the code from BaseHTTPRequestHandler's handle_one_request-method and have overridden the last few lines to finally make my code work.

    All my other attempts (overriding it in the server class, catching exceptions in the request handler or in the main-method) did not seem to work.

    Hope this could help somebody out sometimes.