禁用 mod_wsgi 为 Flask 脚本启动新线程

Disable mod_wsgi starting new threads for Flask script

我正在为 control/measure 外部电子设备设置 RPI3。它使用运行 Flask 的 Apache2 服务器和 mod_wsgi。控件的所有代码都在一个名为 Timer 的单独 class 中,它在 __init__.py Flask 脚本中初始化。控件的主循环在不同的线程上。

无法在文档中找到此功能,但从经验来看,服务器似乎在相同的 __init__.py 上运行,只要它收到的请求很少。如果在新请求到来时脚本正忙,那么服务器会在一个单独的线程上启动一个新的请求。发生这种情况时,Timer class 的原始实例是 "lost in the memory",因为从那里处理请求的当前脚本不知道它。

我的解决方案很长一段时间都是将有关 运行 对象的所有信息写入 json 文件,并设置 Timer把class和__init__.py改成read/write就可以了。我认为这有点狡猾。当然,这以前已经解决过。

所以我想做以下两件事之一:

这些可以做吗?

这是简化的代码。

from flask import Flask, render_template, request
import time
import threading

class Timer:
    def __init__(self):
        #setup variables
        pass

    def mainloop(self):
        while True:
            data = readSensor()
            writeFile(data)
            time.sleep(5)


app = Flask(__name__)

t = Timer()

@app.route('/', methods=['GET', 'POST'])
def homepage():
    if request.method == 'POST':
        return render_template("main.html")
    elif request.method == 'GET':
        return render_template("main.html")


@app.route('/_submit')
def submit():
    t = threading.Thread(target=t.mainloop)
    t.start

if __name__ == "__main__":
    app.run()

您应该尝试

上讨论的方法

Python, WSGI, multiprocessing and shared data

基本上您希望跨 threads/processes

共享数据