Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
723 views
in Technique[技术] by (71.8m points)

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

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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 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")

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...