I am using gunicorn to run my Flask application. I would like to register server hooks to perform some action at the start of the application and before shutting down, but I am confused on how to pass variables to these functions and how to extract variables created within them.
In gunicorn.conf.py:
bind = "0.0.0.0:8000"
workers = 2
loglevel = "info"
preload = True
def on_starting(server):
# register some variables here
print "Starting Flask application"
def on_exit(server):
# perform some clean up tasks here using variables from the application
print "Shutting down Flask application"
In app.py, the sample Flask application:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/hello', methods=['POST'])
def hello_world():
return jsonify(message='Hello World')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=9000, debug=False)
Running gunicorn like so: $ gunicorn -c gunicorn.conf.py app:app
A bit late, but you have access to the flask application instance through server.app.wsgi()
. It returns the same instance used by the workers (the one that is also returned by flask.current_app
).
def on_exit(server):
flask_app = server.app.wsgi()
# do whatever with the flask app
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