我可以在不阻塞主执行线程的情况下以编程方式启动 WSGI 应用程序服务器吗? [英] Can i programmatically start a WSGI application server without blocking the main thread of execution?

查看:34
本文介绍了我可以在不阻塞主执行线程的情况下以编程方式启动 WSGI 应用程序服务器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 python 编写一个 Web 应用程序,并使用 lettucesplinter 为其编写验收测试.

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

为了做到这一点,我需要一个 wsgi 服务器在后台启动我的应用程序,以便应用程序可用于我的测试套件.为此,我一直在另一个线程中启动一个女服务员服务器实例,以便浏览器连接到:

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)

这非常有效 - 正在运行的应用程序实例可用于我的测试套件以设置装置/模拟等,并且服务器可用于我的测试连接.但是,当测试完成时,我无法向服务器发送信号以彻底关闭自身.因此,无论如何我可以以某种方式将 KeyboardInterrupt 发送到我生成的服务器线程(它将被女服务员捕获并提示它干净地关闭),或者失败了,是否存在现有的wsgi 服务器实现,它公开了非阻塞的 start()stop() 方法,我可以使用它们代替女服务员?

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?

推荐答案

将运行 WSGI 服务器的线程标记为守护线程.这样,当您退出主线程时,它不会等待服务器正在运行的线程完成,而只会退出应用程序.

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.

这篇关于我可以在不阻塞主执行线程的情况下以编程方式启动 WSGI 应用程序服务器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆