1+ import socket
12import SocketServer
3+ import threading
24
35from django .conf import settings
46from django .core .handlers .wsgi import WSGIHandler
57from django .core .management import call_command
6- from django .core .servers .basehttp import StoppableWSGIServer , AdminMediaHandler , WSGIServerException
7- from django .test .testcases import TestServerThread
8+ from django .core .servers .basehttp import WSGIServer , AdminMediaHandler , WSGIServerException
89
910from devserver .utils .http import SlimWSGIRequestHandler
1011
1112
12- class ThreadedTestServerThread (TestServerThread ):
13+ class StoppableWSGIServer (WSGIServer ):
14+ """WSGIServer with short timeout, so that server thread can stop this server."""
15+
16+ def server_bind (self ):
17+ """Sets timeout to 1 second."""
18+ WSGIServer .server_bind (self )
19+ self .socket .settimeout (1 )
20+
21+ def get_request (self ):
22+ """Checks for timeout when getting request."""
23+ try :
24+ sock , address = self .socket .accept ()
25+ sock .settimeout (None )
26+ return (sock , address )
27+ except socket .timeout :
28+ raise
29+
30+
31+ class ThreadedTestServerThread (threading .Thread ):
32+ """Thread for running a http server while tests are running."""
33+
34+ def __init__ (self , address , port ):
35+ self .address = address
36+ self .port = port
37+ self ._stopevent = threading .Event ()
38+ self .started = threading .Event ()
39+ self .error = None
40+ super (ThreadedTestServerThread , self ).__init__ ()
41+
1342 def run (self ):
43+ """Sets up test server and database and loops over handling http requests."""
1444 try :
15- wsgi_handler = AdminMediaHandler (WSGIHandler ())
45+ handler = AdminMediaHandler (WSGIHandler ())
1646 server_address = (self .address , self .port )
1747
1848 class new (SocketServer .ThreadingMixIn , StoppableWSGIServer ):
1949 def __init__ (self , * args , ** kwargs ):
2050 StoppableWSGIServer .__init__ (self , * args , ** kwargs )
2151
2252 httpd = new (server_address , SlimWSGIRequestHandler )
23- httpd .set_app (wsgi_handler )
53+ httpd .set_app (handler )
2454 self .started .set ()
2555 except WSGIServerException , e :
2656 self .error = e
@@ -39,3 +69,8 @@ def __init__(self, *args, **kwargs):
3969 # Loop until we get a stop event.
4070 while not self ._stopevent .isSet ():
4171 httpd .handle_request ()
72+
73+ def join (self , timeout = None ):
74+ """Stop the thread and wait for it to finish."""
75+ self ._stopevent .set ()
76+ threading .Thread .join (self , timeout )
0 commit comments