Reputation: 143
#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__'
Upvotes: 9
Views: 4210
Reputation: 53
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
Upvotes: 0
Reputation: 2659
Gunicorn is not running the file, but import
ing 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)
...
Upvotes: 7
Reputation: 10315
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")
Upvotes: 2