I am running my HTTPServer
in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.
The Python documentation states that BaseHTTPServer.HTTPServer
is a subclass of SocketServer.TCPServer
, which supports a shutdown
method, but it is missing in HTTPServer
.
The whole BaseHTTPServer
module has very little documentation :(
I should start by saying that "I probably wouldn't do this myself, but I have in the past". The serve_forever (from SocketServer.py) method looks like this:
You could replace (in subclass)
while 1
withwhile self.should_be_running
, and modify that value from a different thread. Something like:Edit: I dug up the actual code I used at the time:
Another way to do it, based on http://docs.python.org/2/library/basehttpserver.html#more-examples, is: instead of serve_forever(), keep serving as long as a condition is met, with the server checking the condition before and after each request. For example:
I think you can use
[serverName].socket.close()
In my python 2.6 installation, I can call it on the underlying TCPServer - it still there inside your
HTTPServer
:This method I use successfully (Python 3) to stop the server from the web application itself (a web page):
This way, pages served via base address
http://localhost:8080/static/
(examplehttp://localhost:8080/static/styles/common.css
) will be served by the default handler, an access tohttp://localhost:8080/control/stop.html
from the server's computer will displaystop.html
then stop the server, any other option will be forbidden.In python 2.7, calling shutdown() works but only if you are serving via serve_forever, because it uses async select and a polling loop. Running your own loop with handle_request() ironically excludes this functionality because it implies a dumb blocking call.
From SocketServer.py's BaseServer:
Heres part of my code for doing a blocking shutdown from another thread, using an event to wait for completion: