Python 当名称从“应用程序”更改时,Gunicorn 无法找到应用程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33379287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:15:59  来源:igfitidea点击:

Gunicorn can't find app when name changed from "application"

pythonflaskgunicorn

提问by xio

I use gunicorn --workers 3 wsgito run my Flask app. If I change the variable applicationto myapp, Gunicorn gives the error AppImportError: Failed to find application: 'wsgi'. Why am I getting this error and how do I fix it?

gunicorn --workers 3 wsgi用来运行我的 Flask 应用程序。如果我将变量更改applicationmyapp,Gunicorn 会给出错误AppImportError: Failed to find application: 'wsgi'。为什么我会收到此错误以及如何修复它?

myproject.py:

myproject.py

from flask import Flask

myapp = Flask(__name__)

@myapp.route("/")
def hello():
    return 'Test!'

if __name__ == "__main__":
    myapp.run(host='0.0.0.0')

wsgi.py:

wsgi.py

from myproject import myapp

if __name__ == "__main__":
    myapp.run()

采纳答案by davidism

Gunicorn (and most WSGI servers) defaults to looking for the callable named applicationin whatever module you point it at. Adding an alias from myproject import myapp as applicationor application = myappwill let Gunicorn discover the callable again.

Gunicorn(和大多数 WSGI 服务器)默认查找application在您指向它的任何模块中命名的可调用对象。添加别名from myproject import myapp as applicationapplication = myapp将让 Gunicorn 再次发现可调用对象。

However, the wsgi.pyfile or the alias aren't needed, Gunicorn can be pointed directly at the real module and callable.

但是,wsgi.py不需要文件或别名,Gunicorn 可以直接指向真正的模块并可调用。

gunicorn myproject:myapp --workers 16
# equivalent to "from myproject import myapp as application"

Gunicorn can also call an app factory, optionally with arguments, to get the application object. (This briefly did not work in Gunicorn 20, but was added backin 20.0.1.)

Gunicorn 还可以调用应用程序工厂(可选带参数)来获取应用程序对象。(这在 Gunicorn 20 中暂时不起作用,但在 20.0.1 中重新添加。)

gunicorn 'myproject.app:create_app("production")' --workers 16
# equivalent to:
# from myproject.app import create_app
# application = create_app("production")


For WSGI servers that don't support calling a factory, or for other more complicated imports, a wsgi.pyfile is needed to do the setup.

对于不支持调用工厂的 WSGI 服务器,或者对于其他更复杂的导入,wsgi.py需要一个文件来进行设置。

from myproject.app import create_app
app = create_app("production")
gunicorn wsgi:app --workers 16

回答by duhaime

If you're trying to serve an app with variable name appwithin server/cats.py, you can start the server on port 8000 as follows:

如果您尝试为变量名称app在 内的应用程序提供服务server/cats.py,您可以在端口 8000 上启动服务器,如下所示:

gunicorn server.cats:app -b 0.0.0.0:8000