I'm attempting a wxPython app which runs an HTTP server in a separate
thread. I've subclassed HTTPServer and then run its handle_request() method
from the thread's run() directly, while a stop event is not set. The code
which runs and joins the thread is here, called from menu items for the
moment:
def onStart(self, event):
self.testthread = httpdThread()
self.testthread.start()
def onStop(self, event):
self.testthread.join()
Below is the code, with the http connection to cause the handler to actually
exit, as handle_request blocks on an accept() further down the call chain.
A non-blocking socket doesn't seem to work here, so in the meantime I'm just
performing a 'GET /' to give the server the one last request it needs to
shut down. It's in a try/except clause since there's a race condition,
where if another outside request hits it before its own, an exception will
be raised (as the server won't be there anymore).
The GUI does stay responsive throughout all this; at least that much is
working correctly.
It is expected that information the server will need to activate itself may
change over the course of execution (IP address, port, etc.), so the server
will need to be restarted occasionally. Is there a more elegant way of
achieving an immediate shudown?
···
----
from SocketServer import *
from BaseHTTPServer import *
from threading import *
from httplib import *
class Server(ThreadingMixIn, HTTPServer):
def __init__(self):
HTTPServer.__init__(self, ("0.0.0.0", 80), Handler)
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.wfile.write("Succeeded.\n")
class httpdThread(Thread):
def __init__(self):
self._stopevent = Event()
Thread.__init__(self)
def run(self):
svr = Server()
while not self._stopevent.isSet():
svr.handle_request()
def join(self,timeout=None):
self._stopevent.set()
try:
HTTPConnection('127.0.0.1').request("GET", "/")
except:
pass
Thread.join(self, timeout)
----
Win2K, Python 2.2.1, wxPython 2.3.
Any advice would be appreciated.
J.