Skip to content

Commit bce568c

Browse files
committed
Added app.stop() by making server a global variable. webpy#122
Thanks @Irfy for the testcase.
1 parent c542f9b commit bce568c

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

test/application.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import webtest
22
import time
3+
import threading
34

45
import web
56
import urllib
@@ -324,5 +325,23 @@ def f(script_name=""):
324325
self.assertEquals(f(''), 'foo=bar; Path=/')
325326
self.assertEquals(f('/admin'), 'foo=bar; Path=/admin/')
326327

328+
def test_stopsimpleserver(self):
329+
urls = (
330+
'/', 'index',
331+
)
332+
class index:
333+
def GET(self):
334+
pass
335+
app = web.application(urls, locals())
336+
thread = threading.Thread(target=app.run)
337+
338+
thread.start()
339+
time.sleep(1)
340+
self.assertTrue(thread.is_alive())
341+
342+
app.stop()
343+
thread.join(timeout=1)
344+
self.assertFalse(thread.is_alive())
345+
327346
if __name__ == '__main__':
328347
webtest.main()

web/application.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import webapi as web
66
import webapi, wsgi, utils
77
import debugerror
8+
import httpserver
9+
810
from utils import lstrips, safeunicode
911
import sys
1012

@@ -309,6 +311,13 @@ def run(self, *middleware):
309311
function.
310312
"""
311313
return wsgi.runwsgi(self.wsgifunc(*middleware))
314+
315+
def stop(self):
316+
"""Stops the http server started by run.
317+
"""
318+
if httpserver.server:
319+
httpserver.server.stop()
320+
httpserver.server = None
312321

313322
def cgirun(self, *middleware):
314323
"""

web/httpserver.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,13 +131,18 @@ def __init__(self, func, server_address):
131131
print "http://%s:%d/" % server_address
132132
WSGIServer(func, server_address).serve_forever()
133133

134+
# The WSGIServer instance.
135+
# Made global so that it can be stopped in embedded mode.
136+
server = None
137+
134138
def runsimple(func, server_address=("0.0.0.0", 8080)):
135139
"""
136140
Runs [CherryPy][cp] WSGI server hosting WSGI app `func`.
137141
The directory `static/` is hosted statically.
138142
139143
[cp]: http://www.cherrypy.org
140144
"""
145+
global server
141146
func = StaticMiddleware(func)
142147
func = LogMiddleware(func)
143148

@@ -152,6 +157,7 @@ def runsimple(func, server_address=("0.0.0.0", 8080)):
152157
server.start()
153158
except (KeyboardInterrupt, SystemExit):
154159
server.stop()
160+
server = None
155161

156162
def WSGIServer(server_address, wsgi_app):
157163
"""Creates CherryPy WSGI server listening at `server_address` to serve `wsgi_app`.

0 commit comments

Comments
 (0)