问题描述
我使用 gunicorn --workers 3 wsgi
来运行我的 Flask 应用程序.如果我将变量 application
更改为 myapp
,Gunicorn 会给出错误 AppImportError: Failed to find application: 'wsgi'
.为什么我会收到这个错误,我该如何解决?
I use gunicorn --workers 3 wsgi
to run my Flask app. If I change the variable application
to myapp
, Gunicorn gives the error AppImportError: Failed to find application: 'wsgi'
. Why am I getting this error and how do I fix it?
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
:
from myproject import myapp
if __name__ == "__main__":
myapp.run()
推荐答案
Gunicorn(和大多数 WSGI 服务器)默认在您指向的任何模块中查找名为 application
的可调用对象.添加别名 from myproject import myapp as application
或 application = myapp
将使 Gunicorn 再次发现可调用对象.
Gunicorn (and most WSGI servers) defaults to looking for the callable named application
in whatever module you point it at. Adding an alias from myproject import myapp as application
or application = myapp
will let Gunicorn discover the callable again.
然而,wsgi.py
文件或别名不是必需的,Gunicorn 可以直接指向真正的模块并且可以调用.
However, the wsgi.py
file or the alias aren't needed, Gunicorn can be pointed directly at the real module and callable.
gunicorn myproject:myapp --workers 16
# equivalent to "from myproject import myapp as application"
Gunicorn 还可以调用应用程序工厂(可选带参数)来获取应用程序对象.(这在 Gunicorn 20 中暂时不起作用,但在 20.0.1 中重新添加.)
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 back in 20.0.1.)
gunicorn 'myproject.app:create_app("production")' --workers 16
# equivalent to:
# from myproject.app import create_app
# application = create_app("production")
对于不支持调用工厂的 WSGI 服务器,或者对于其他更复杂的导入,需要一个 wsgi.py
文件来进行设置.
from myproject.app import create_app
app = create_app("production")
gunicorn wsgi:app --workers 16
这篇关于当名称从“应用程序"更改时,Gunicorn 无法找到应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!