Permalink
Browse files

Added app.stop() by making server a global variable. #122

Thanks @Irfy for the testcase.
  • Loading branch information...
1 parent c542f9b commit bce568cbc324b56f155faeb1483c47910dfd4a7e @anandology anandology committed May 24, 2012
Showing with 34 additions and 0 deletions.
  1. +19 −0 test/application.py
  2. +9 −0 web/application.py
  3. +6 −0 web/httpserver.py
View
@@ -1,5 +1,6 @@
import webtest
import time
+import threading
import web
import urllib
@@ -324,5 +325,23 @@ def f(script_name=""):
self.assertEquals(f(''), 'foo=bar; Path=/')
self.assertEquals(f('/admin'), 'foo=bar; Path=/admin/')
+ def test_stopsimpleserver(self):
+ urls = (
+ '/', 'index',
+ )
+ class index:
+ def GET(self):
+ pass
+ app = web.application(urls, locals())
+ thread = threading.Thread(target=app.run)
+
+ thread.start()
+ time.sleep(1)
+ self.assertTrue(thread.is_alive())
+
+ app.stop()
+ thread.join(timeout=1)
+ self.assertFalse(thread.is_alive())
+
if __name__ == '__main__':
webtest.main()
View
@@ -5,6 +5,8 @@
import webapi as web
import webapi, wsgi, utils
import debugerror
+import httpserver
+
from utils import lstrips, safeunicode
import sys
@@ -309,6 +311,13 @@ def run(self, *middleware):
function.
"""
return wsgi.runwsgi(self.wsgifunc(*middleware))
+
+ def stop(self):
+ """Stops the http server started by run.
+ """
+ if httpserver.server:
+ httpserver.server.stop()
+ httpserver.server = None
def cgirun(self, *middleware):
"""
View
@@ -131,13 +131,18 @@ def __init__(self, func, server_address):
print "http://%s:%d/" % server_address
WSGIServer(func, server_address).serve_forever()
+# The WSGIServer instance.
+# Made global so that it can be stopped in embedded mode.
+server = None
+
def runsimple(func, server_address=("0.0.0.0", 8080)):
"""
Runs [CherryPy][cp] WSGI server hosting WSGI app `func`.
The directory `static/` is hosted statically.
[cp]: http://www.cherrypy.org
"""
+ global server
func = StaticMiddleware(func)
func = LogMiddleware(func)
@@ -152,6 +157,7 @@ def runsimple(func, server_address=("0.0.0.0", 8080)):
server.start()
except (KeyboardInterrupt, SystemExit):
server.stop()
+ server = None
def WSGIServer(server_address, wsgi_app):
"""Creates CherryPy WSGI server listening at `server_address` to serve `wsgi_app`.

0 comments on commit bce568c

Please sign in to comment.