Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

code before app.run() can not be run in gunicorn+flask

Tags:

flask

gunicorn

#main.py
from flask import Flask

app = Flask(__name__)

if __name__ == '__main__':    
    print("before app run")
    app.run()  # , threaded=True host='0.0.0.0', debug=True, port=5000

Run gunicorn as follow:

gunicorn -b 0.0.0.0:8000 --preload main:app

the result will not print “before app unn”. How can i run the print code? if i don't want to place print outside of if __name__ == '__main__'

like image 860
dianesong Avatar asked Jun 07 '17 07:06

dianesong


People also ask

What is __ main __ In Flask?

__main__ — Top-level code environment. In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.

Can you run Gunicorn on Windows?

Installing. Gunicorn is easy to install, as it does not require external dependencies or compilation. It runs on Windows only under WSL. Create a virtualenv, install your application, then install gunicorn .


2 Answers

Gunicorn is not running the file, but importing it. That means that __name__ != "__main__" and your code never gets run.

Gunicorn then manually calls app.run() itself, after importing your file.

The solution is to make sure that your code is run at import time:

> cat main.py
from flask import Flask

app = Flask(__name__)

print "before main stanza"
if __name__ == "__main__":
    print "in main stanza"
    app.run()

And then running the app:

> gunicorn -b 0.0.0.0:8000 --preload main:app
before main stanza
[2017-06-07 08:33:15 +0100] [8865] [INFO] Starting gunicorn 19.7.1
[2017-06-07 08:33:15 +0100] [8865] [INFO] Listening at: http://0.0.0.0:8000 (8865)
...
like image 189
tehwalrus Avatar answered Sep 28 '22 07:09

tehwalrus


Actually that will print before app run when you run this application with python main.py

It's not possible with Gunicorn though you can try before_first_request that will do the trick

@app.before_first_request
def execute_this():
    print("before app run")
like image 43
Raja Simon Avatar answered Sep 28 '22 09:09

Raja Simon