1
+ import socket
1
2
import SocketServer
3
+ import threading
2
4
3
5
from django .conf import settings
4
6
from django .core .handlers .wsgi import WSGIHandler
5
7
from 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
8
9
9
10
from devserver .utils .http import SlimWSGIRequestHandler
10
11
11
12
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
+
13
42
def run (self ):
43
+ """Sets up test server and database and loops over handling http requests."""
14
44
try :
15
- wsgi_handler = AdminMediaHandler (WSGIHandler ())
45
+ handler = AdminMediaHandler (WSGIHandler ())
16
46
server_address = (self .address , self .port )
17
47
18
48
class new (SocketServer .ThreadingMixIn , StoppableWSGIServer ):
19
49
def __init__ (self , * args , ** kwargs ):
20
50
StoppableWSGIServer .__init__ (self , * args , ** kwargs )
21
51
22
52
httpd = new (server_address , SlimWSGIRequestHandler )
23
- httpd .set_app (wsgi_handler )
53
+ httpd .set_app (handler )
24
54
self .started .set ()
25
55
except WSGIServerException , e :
26
56
self .error = e
@@ -39,3 +69,8 @@ def __init__(self, *args, **kwargs):
39
69
# Loop until we get a stop event.
40
70
while not self ._stopevent .isSet ():
41
71
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