我有一个使用 Pyramid 网络框架编写的应用程序。但是我需要 WebSockets 的异步功能。这是在 Tornado 中实现的功能。我尝试像这样将 Pyramid 与 Tornado 结合使用:
app = tornado.web.Application([
(r'/', IndexHandler),
])
def build_tornado_app():
app.listen(6544)
tornado.ioloop.IOLoop.instance().start()
# This function returns a Pyramid WSGI application
def main(global_config, **settings):
build_tornado_app()
# ... config routes, database session etc.
config.scan()
return config.make_wsgi_app()
不幸的是,启动 Tornado 应用程序(使用 start() 函数)会阻塞执行链。
我可以在不阻塞 Pyramid 执行链的情况下启动 Tornado 应用程序吗?
请您参考如下方法:
要使用 Tornado 的异步特性(包括 websockets),你必须使用 Tornado 的 HTTPServer 而不是运行在 WSGI 容器中。然后,您可以使用 tornado.web.WSGIContainer 在 Tornado 内部运行 Pyramid ,完全替换您当前的 WSGI 容器。
但是,Tornado 的 WSGIContainer 是单线程的,对于大多数使用 WSGI 框架构建的应用程序来说,这不是一个好的选择。除非你非常需要在同一个进程中运行 Pyramid 和 Tornado,否则我建议将它们分开,在你的 Pyramid 应用程序旁边运行一个纯 Tornado websocket 进程。
