Can i programmatically start a WSGI application se

2019-05-06 18:52发布

问题:

I'm writing a web application in python, and using lettuce with splinter to write acceptance tests for it.

In order to do this, I need to get a wsgi server to start my application in the background, so that the application is available for my test suite. To do this, I've been spinning up a waitress server instance in another thread, for the browser being driven to connect to:

def setUp():
    base = os.path.dirname(__file__) + "/../../.."
    world.app = loadapp('config:test.ini', relative_to=base)
    world.server_thread = thread.start_new_thread(serve_app,  (world.app,))

def serve_app(app):
    serve(app, host='0.0.0.0', port=7654)

This works quite nicely - The running application instance is available to my test suite in order to set up fixtures / mocks etc, and the server is available for my tests to connect to. However, when the tests finish, I've no way of sending a signal to the server to shut itself down cleanly. Therefore, is there anyway I can somehow either send a KeyboardInterrupt to the server thread I spawn (which will be caught by waitress and will prompt it to shut down cleanly), or failing that, is there an existing wsgi server implementation which exposes non-blocking start() and stop() methods that I could employ instead of waitress?

回答1:

Mark the thread you run the WSGI server in as a daemon thread. That way when you exit the main thread it will not wait for the thread the server is running in to complete and will just exit the application.



回答2:

You don't necessarily need WSGI server to unit-test a WSGI app, example.

For you acceptance tests you could start the server in a separate process and send SIGINT when you're done.

If you'd like to stick with your current setup; you could run the server in the main thread and your tests in background threads. Then you could send KeyboardInterrupt to the main thread from subthreads.



回答3:

Is the problem just that the process won't shut down?

It's been a while since I've used Python for web development, so I've no experience of these libraries, but if shutting down is the problem it looks like a good scenario to use daemon threads.

Mentioned here: http://docs.python.org/library/threading.html