Stopping a *HTTPServer

Alex Martelli aleaxit at yahoo.com
Sat May 26 05:10:32 EDT 2001


"SteveR" <steve at grandfathersaxe.demon.co.uk> wrote in message
news:7t61iTARL1D7IwgW at grandfathersaxe.demon.co.uk...
> David LeBlanc <whisper at oz.nospamnet> wrote:
> >In article <67abb823.0105250734.24705e9d at posting.google.com>,
> >mt_horeb at yahoo.com says...
> >> Here's the situation - I'm building a quick-and-dirty application that
> >> serves CGI and HTML via the CGIHTTPServer module.  So far, so good.
> >> The only issue that I am having is that I cannot figure out how to
> >> stop the server once I've started it with serve_forever().
    ...
> I would like to be able to stop one of these servers, *under program
> control*.  My application has a "hidden" admin page which allows the
> server to be stopped.  At the moment, I'm using os._exit, but this is
> just as inelegant as Ctrl-C/Ctrl-Break.
>
> Is there a tidier way than os._exit?

What about subclassing and overriding serve_forever()?  Right now
it does:

    def serve_forever(self):
        """Handle one request at a time until doomsday."""
        while 1:
            self.handle_request()

and it's clearly no rocket science to override this with, e.g.:

    def serve_forever(self):
        """Handle one request at a time until doomsday... almost."""
        self.proceed = 1
        while self.proceed:
            self.handle_request()

now, from within your handle_request method, or methods called
from it, you can set the .proceed attribute to 0 and when handle_request
finishes the server will shut down.  Can be made subtler of course
(keep serving as long as requests are already queued-up in some
way, etc), but this might do, and it seems crystal-simple.


Alex






More information about the Python-list mailing list