Initialising a Flask app running with Apache and mod_wsgi

拟墨画扇 提交于 2021-01-28 07:34:02

问题


I've got a Flask app running under Apache using mod_wsgi. The app needs to do do some initialisation, including setting some top-level variables that need to be accessible inside the request handlers, before it receives any requests. At the moment this initialisation code is just top-level statements in app.py before the request handling methods:

from flask import Flask, Response, request

<other app imports>

APP = Flask(__name__)

# initialisation code

@APP.route(<URL for request #1>)
def request_handler_1():
    # request handler code

@APP.route(<URL for request #2>)
def request_handler_2():
    # request handler code

The application's wsgi file looks like this:

#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/myapp")

from myapp.app import APP as application
application.secret_key = <secret key>

I've noticed that the initialisation code is not called until the first request is received. How can I made the initialisation code be executed when the app is loaded by mod_wsgi, before any requests are received?


回答1:


It is happening on first request because by default mod_wsgi will only load your WSGI script file when the first request arrives. That is, it lazily loads your WSGI application.

If you want to force it to load your WSGI application when the process first starts, then you need to tell mod_wsgi to do so.

If you have configuration like:

WSGIDaemonProcess myapp
WSGIProcessGroup myapp
WSGIApplicationGroup %{GLOBAL}
WSGIScriptAlias / /some/path/app.wsgi

change it to:

WSGIDaemonProcess myapp
WSGIScriptAlias / /some/path/app.wsgi process-group=myapp application-group=%{GLOBAL}

It is only when both process group and application group are specified on WSGIScriptAlias, rather than using the separate directives, that mod_wsgi can know up front what process/interpreter context the WSGI application will run in and so preload the WSGI script file.

BTW, if you weren't already using mod_wsgi daemon mode (the WSGIDaemonProcess directive), and forcing the main interpreter context (the WSGIApplicationGroup %{GLOBAL} directive), you should be, as that is the preferred setup.



来源:https://stackoverflow.com/questions/42439210/initialising-a-flask-app-running-with-apache-and-mod-wsgi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!