Javiar Sandra
Javiar Sandra

Reputation: 845

Gunicorn does not execute statements within main

from flask import Flask, request, jsonify


app = Flask(__name__)
@app.route('/api', methods=['POST'])
def predict():
    pass
    #Some statements to predict something


if __name__ == '__main__':
    print("Hello World")
    app.run(host='0.0.0.0', debug=True)

When I run as gunicorn -b 0.0.0.0 app:app I do not see the print statement. However when I run as python app.py, the "Hello World" gets printed. The app runs but it does not execute the print statement. Any idea what causes the Gunicorn to ignore what is within main()?

Upvotes: 3

Views: 1283

Answers (1)

ACL
ACL

Reputation: 509

When you run as gunicorn -b 0.0.0.0 app:app, gunicorn will only import the app from your app.py file. It will skip statements from the if __name__ == '__main__' block and hence you're not seeing the output from the print statement.

But when you run as python app.py, if __name__ == '__main__' block will be the entry point and hence print statement gets executed.

Also note that, the app.run(host='0.0.0.0', debug=True) line in if __name__ == '__main__' will start the development server and not the gunicorn server.

Attaching the link here for the similar question: code before app.run() can not be run in gunicorn+flask

Upvotes: 1

Related Questions