Shutting down an HTTPServer

For integration tests it can be helpful to have a fake HTTP server whose behaviour the tests can control. All necessary building blocks are even included in Python standard library. However, the BaseHTTPServer is surprisingly hard to shut down properly, so that it gives up the socket and everything.

While working on gocept.selenium, we came up with some code that does the trick (together with Jan-Wijbrand Kolman and Jan-Jaap Driessen).

class HTTPServer(BaseHTTPServer.HTTPServer):

    _continue = True

    def serve_until_shutdown(self):
        while self._continue:

    def shutdown(self):
        self._continue = False
        # We fire a last request at the server in order to take it out of the
        # while loop in `self.serve_until_shutdown`.
                'http://%s:%s/' % (self.server_name, self.server_port))
        except urllib2.URLError:
            # If the server is already shut down, we receive a socket error,
            # which we ignore.

You might use this in a zope.testrunner layer like this:

class SilentRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):

    def log_message(self, format, *args):

class HTTPServerLayer(object):

    host = 'localhost'

    def setUp(self):
        self.server = None
        self.port = random.randint(30000, 40000)

    def start_server(self):
        self.server = HTTPServer((, self.port), SilentRequestHandler)
        self.server_thread = threading.Thread(
        self.server_thread.daemon = True
        # Kludge: Wait a little as it sometimes takes a while to get the server
        # started.

    def stop_server(self):
        if self.server is None:

    def tearDown(self):



Author: Wolfgang Schnerring

Wolfgang is a software developer working at gocept.

2 thoughts on “Shutting down an HTTPServer”

  1. Why did you subclass BaseHTTPServer.HTTPServer?
    If you’re using a separate thread to handle requests you can use serve_forever to start and shutdown to stop. It seems to me that it’s much more simpler.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s