In my python script, I am trying to run a web server:
server = BaseHTTPServer.HTTPServer((\'127.0.0.1\',8080), RequestHandler)
I have a req
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
timeout = 60 # StreamRequestHandler.setup
def do_GET(self):
# Doing Some Stuff.
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):
# ...
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def __init__(self, request, client_address, server):
BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, request, client_address, server)
self.timeout = 60
As pointed out by Tey' in TinBane's answer, timeout
attribute will not work with serve_forever()
method, as stated in the doc:
The workaround is to use a custom loop for handling the request as pointed out by user3483992
while True: server.handle_request()
handle_request()
will then trigger the method handle_timeout()
at the end of the given timeout as expected:
...except the handle_timeout method is doing nothing:
A solution is then to provide another implementation for this method, such as (credit here):
server.handle_timeout = lambda: (_ for _ in ()).throw(TimeoutError())
In short:
try:
server = HTTPServer(('', PORT_NUMBER), `yourAwesomeRequestHandler`)
server.timeout = 10
server.handle_timeout = lambda: (_ for _ in ()).throw(TimeoutError())
while True: server.handle_request()
except TimeoutError:
// TODO
I managed to get timeouts working for HTTP requests with
self.rfile._sock.settimeout(60)
Hope this helps
timeout = 0.1 # seconds
class WebHTTPServer(BaseHTTPServer.HTTPServer):
def server_bind(self):
BaseHTTPServer.HTTPServer.server_bind(self)
self.socket.settimeout(timeout)
class WebReqHandler(BaseHTTPServer.BaseHTTPRequestHandler):
<etc>
if __name__ == '__main__':
server = WebHTTPServer(('',port), WebReqHandler)
while 1:
server.handle_request()
<do other things>