Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use variables created in gunicorn's server hooks?

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

like image 278
Python Novice Avatar asked Oct 30 '22 16:10

Python Novice


1 Answers

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
like image 129
engineerC Avatar answered Nov 15 '22 05:11

engineerC