如何使用gunicorn运行Flask应用程序?

Dec*_*eck 5 python flask gunicorn

该问题可以分为两个单独的部分。

  1. 我有以下项目结构

    |- project
    |   |-- app/ - directory with actual project code
    |   |-- app.py - imports something from app/ and call create_app
    
    Run Code Online (Sandbox Code Playgroud)

    当我运行时gunicorn,我应该将他指向app实际在app.py. 所以我收到一个错误,因为gunicorn 将其视为app:app一个包。唯一的办法是重命名一些东西?

  2. 我使用工厂方法来创建应用程序。所以我在 app.py 中导入create_app函数并将其传递给Managerfrom flask.ext.script。我将管理器对象传递给gunicorn。在这种情况下,gunicorn 可以正确运行,但是一旦第一个请求到来,我就会收到以下错误:

    [2015-03-25 15:38:11 +0000] [14395] [ERROR] Error handling request
    Traceback (most recent call last):
      File "/opt/env/local/lib/python2.7/site-packages/gunicorn/workers/async.py", line 52, in handle
    self.handle_request(listener_name, req, client, addr)
      File "/opt/env/local/lib/python2.7/site-packages/gunicorn/workers/ggevent.py", line 159, in handle_request
    super(GeventWorker, self).handle_request(*args)
      File "/opt/env/local/lib/python2.7/site-packages/gunicorn/workers/async.py", line 105, in handle_request
        respiter = self.wsgi(environ, resp.start_response)
    TypeError: __call__() takes at most 2 arguments (3 given)
    
    Run Code Online (Sandbox Code Playgroud)

    也许我可以创建一些文件wsgi.py并为gunicorn提供当前的应用程序?

dav*_*ism 4

如果两个名为“app”的东西位于 Python 路径中的同一目录中,则会出现问题。

您需要将 Flask 应用程序实例直接传递给gunicorn。命令行管理器不是 WSGI 应用程序,这就是您收到该错误的原因。

您只需将gunicorn 直接指向对您的应用程序工厂的调用,无需任何中间代码。

gunicorn app:create_app()
Run Code Online (Sandbox Code Playgroud)