我正在使用 gunicorn 来运行我的 Flask 应用程序。我想注册服务器 Hook 以在应用程序启动时和关闭之前执行一些操作,但我对如何将变量传递给这些函数以及如何提取在它们中创建的变量感到困惑。
在 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"
在 app.py 中,示例 Flask 应用程序:
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)
像这样运行 gunicorn:$ gunicorn -c gunicorn.conf.py app:app
请您参考如下方法:
有点晚了,但是您可以通过 server.app.wsgi() 访问 flask 应用程序实例。它返回工作人员使用的相同实例(flask.current_app 也返回的实例)。
def on_exit(server):
flask_app = server.app.wsgi()
# do whatever with the flask app
