#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__'
__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.
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 .
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)
...
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With