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

3

9
#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__'

Galliett answered 7/6, 2017 at 7:13 Comment(0)
J
7

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)
...
Jordanna answered 7/6, 2017 at 7:36 Comment(0)
S
2

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")
Standford answered 7/6, 2017 at 7:19 Comment(0)
S
0

The cleaner way to do this is with the decorator as mentioned in the other answer but @app.before_first_request is deprecated since Flask 2.2 and will be removed in 2.3 as mentioned here

Use this instead:

with app.app_context():
  print("before app run")

If you run the app with debug=True, then the code inside tends to run twice. Just turn it off to prevent that

Supposal answered 15/6, 2023 at 3:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.