Apache 配置 mod_wsgi 在每次调用时调用 before_first_request

Apache configure with mod_wsgi calling before_first_request on each call

我想将 6GB 的文件加载到内存中,这样如果我收到请求就不必再次加载它。所以我能够通过添加简单的装饰器@app.before_first_request在烧瓶服务器上实现这一点,但是当我将apache与同一个应用程序集成时,它会在每个请求之前调用这个函数。

我的代码如下:

route.py

@app.before_first_request
def initialize():
    global SRC_PATH, MODEL
    path = SRC_PATH
    print("Loading Core files from {}".format(path))
    MODEL = Model.load(path+utils.MODEL_EXT)
    print("Loaded all files in memory")

@app.route("/test",methods=['POST'])
def search_index():
    # MyCode:
    return "some response"

我的 apache 配置是:

<VirtualHost *>
    WSGIDaemonProcess yourapplication user=ubuntu group=www-data
    WSGIScriptAlias / /xxx/app.wsgi
    <Directory /xxx/>
        WSGIProcessGroup yourapplication
        WSGIApplicationGroup %{GLOBAL}
        Order deny,allow
        Allow from all
    </Directory>
<VirtualHost *>

和app.wsgi

import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0, "/xxx/")
from route import app as application

现在,在我的 Apache 日志中,它正在加载核心文件的每个请求: apache.log

[Sun Oct 29 06:21:14.691075 2017] [wsgi:error] [pid 22906:tid 140496053819136] Loading Core files from /xxx
[Sun Oct 29 06:21:20.919143 2017] [wsgi:error] [pid 22906:tid 140496053819136] Loaded all files in memory

虽然我希望它在第一次请求时或什至之前加载并永久保存在内存中?

我的问题是在代码中我使用多处理来加载文件。

所以我没有进行多进程,而是将其更改为多线程。

所以之前使用多进程的代码如下:

from multiprocessing import Pool

我已经更新到

from multiprocessing.dummy import Pool

其中 multiprocessing.dummy 是基于线程而不是基于进程的。