简体   繁体   English

初始化使用Apache和mod_wsgi运行的Flask应用

[英]Initialising a Flask app running with Apache and mod_wsgi

I've got a Flask app running under Apache using mod_wsgi. 我有一个使用mod_wsgi在Apache下运行的Flask应用。 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: 目前,此初始化代码只是app.py中请求处理方法之前的顶级语句:

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: 该应用程序的wsgi文件如下所示:

#!/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? 在收到任何请求之前,如何通过mod_wsgi加载应用程序时执行初始化代码?

It is happening on first request because by default mod_wsgi will only load your WSGI script file when the first request arrives. 这是在第一个请求上发生的,因为默认情况下,mod_wsgi仅在第一个请求到达时才加载WSGI脚本文件。 That is, it lazily loads your WSGI application. 也就是说,它会延迟加载WSGI应用程序。

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. 如果要在进程首次启动时强制其加载WSGI应用程序,则需要告诉mod_wsgi这样做。

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. 只有在WSGIScriptAlias上同时指定了进程组和应用程序组时,而不是使用单独的指令,mod_wsgi才可以预先知道WSGI应用程序将在哪个进程/解释器上下文中运行,并因此预加载WSGI脚本文件。

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. 顺便说一句,如果您尚未使用mod_wsgi守护程序模式( WSGIDaemonProcess指令),并强制使用主解释器上下文( WSGIApplicationGroup %{GLOBAL}指令),则应该使用,因为这是首选设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM