【问题标题】:Port Tornado application to gunicornPort Tornado 应用到 gunicorn
【发布时间】:2019-09-23 16:31:12
【问题描述】:

我正在运行一个带有 Tornado 应用程序的 Python api 服务器。 我的 Tornado 应用程序使用 tornado.web 并定义为

from tornado import web

def application():

    handlers = [
        # apis
        (r'/api/1', th.APIHandler1),
        (r'/api/2', th.APIHandler2)
    ]

    settings = dict()
    return web.Application(handlers, **settings) 

所以它像在 IOLoop 中运行

app = application()
app.listen(int(PORT))
ioloop.IOLoop.instance().start()

所以它不是一个 WSGI 应用程序。处理程序通常使用@tornado.web.asynchronous 模式进行装饰,对于CPU 密集型任务使用@tornado.gen.coroutine 模式,或者在某些特定情况下使用@tornado.concurrent.run_on_executor 装饰器作为线程池中的线程运行的长时间任务。在这种特定情况下,我使用 bounded thread pool executor 之类的:

class MyHandler2(tornado.web.RequestHandler):
    executor = BoundedThreadPoolExecutor(max_workers=5)
    @tornado.concurrent.run_on_executor
    def get(self, *args):

我想将此移植到gunicorn 以利用分叉前工作人员的方法。 我研究过的一个可能的解决方案是 gunicorn multi app pattern,它应该看起来像:

from routes import Mapper
from test import app as apiHandler1
from test import app as apiHandler2


class Application(object):
    def __init__(self):
        self.map = Mapper()
        self.map.connect('app1', '/api/1', app=apiHandler1)
        self.map.connect('app2', '/api/2', app=apiHandler2)

    def __call__(self, environ, start_response):
        match = self.map.routematch(environ=environ)
        if not match:
            return self.error404(environ, start_response)
        return match[0]['app'](environ, start_response)

app = Application()

没有关于将 Tornado 异步应用程序移植到 gunicorn wsgi 应用程序的具体文档,所以我的问题是这种方法是否正确。

【问题讨论】:

    标签: python python-3.x tornado gunicorn


    【解决方案1】:

    Tornado 不是基于 WSGI 的框架,因此不能在 WSGI 应用程序服务器中使用(在旧版本的 Tornado 中,可以以 WSGI 兼容模式运行 Tornado 应用程序的子集,但在龙卷风 6.0)。 Gunicorn 有一个特定于 Tornado 的 worker_class,必须改为使用它。

    【讨论】:

    • 是否有任何带有 Gunicorn 的龙卷风 worker_class 的示例代码/视频。谢谢
    猜你喜欢
    • 2015-03-06
    • 1970-01-01
    • 2017-05-04
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    • 2015-12-18
    • 2014-07-19
    相关资源
    最近更新 更多