问题
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
回答1:
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):
# ...
回答2:
I actually found that setting a value for self.timeout in def setup didn't work if I then called the superclass. It looks like the Handler's setup and init methods aren't called during creation of the HTTPServer instance. I used pydevd to confirm this.
So, I took a backward step:
httpd = BaseHTTPServer.HTTPServer(server_address, MyHttpHandler)
httpd.timeout = 10
Which works perfectly, and without overriding core code, or building your own derivative classes. It looks like you'd have to overwrite the HTTPServer code, rather than the Handler code, if you wanted to do it that way.
回答3:
I managed to get timeouts working for HTTP requests with
self.rfile._sock.settimeout(60)
Hope this helps
回答4:
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
timeout = 60 # StreamRequestHandler.setup
def do_GET(self):
# Doing Some Stuff.
回答5:
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def __init__(self, request, client_address, server):
BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, request, client_address, server)
self.timeout = 60
回答6:
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>
来源:https://stackoverflow.com/questions/4419650/how-to-implement-timeout-in-basehttpserver-basehttprequesthandler-python