How do I run a flask app in gunicorn if I used the application factory pattern?

FlaskGunicorn

Flask Problem Overview


I wrote a flask app using the application factory pattern. That means it doesn't create an app instance automatically when you import it. You have to call create_app for that. Now how do I run it in gunicorn?

Flask Solutions


Solution 1 - Flask

Create a file wsgi.py under your project with the following contents, then point Gunicorn at it.

from my_project import create_app

app = create_app()

gunicorn -w 4 my_project.wsgi:app
# -w 4 specifies four worker processes

If you're using the application factory pattern, Gunicorn allows specifying a function call like my_project:create_app(). For most cases, you can the skip making a wsgi.py file and tell Gunicorn how to create your app directly.

gunicorn -w 4 "my_project:create_app()"

Note that the quotes are necessary in some shells where parentheses have special meaning.

Solution 2 - Flask

You need to create_app() with specific factory config in run.py. See the code below:

from your_app import create_app

if __name__ == "__main__":
    app = create_app(os.getenv('FLASK_CONFIG') or 'dev')
    app.run()

And then, you could run command gunicorn -w 4 -b 0.0.0.0:5000 run:create_app('dev') to run the application.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick RetallackView Question on Stackoverflow
Solution 1 - FlaskdavidismView Answer on Stackoverflow
Solution 2 - FlasksudozView Answer on Stackoverflow