Search code examples
flaskgunicorn

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


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


Solution

  • 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)
    ...