Python 我能';t使用apache'连接烧瓶中的背景线程;s mod_wsgi

Python 我能';t使用apache'连接烧瓶中的背景线程;s mod_wsgi,python,multithreading,apache,flask,mod-wsgi,Python,Multithreading,Apache,Flask,Mod Wsgi,我正在使用Flask+Apache+mod_wsgi构建一个web服务器。我需要在我的web服务器中启动一个后台线程,以便定期做一些事情。一切正常,应用程序启动,线程工作,但我不能加入它。以下是一些代码片段: .wsgi文件 main.py 因此,在app.log中,我只看到“app start” 也许,还有其他方法可以在apache和wsgi shutdown上加入我的线程,而不仅仅是使用atexit模块。看看如何在: 在mod_wsgi下,使用atexit模块是触发进程关闭操作的唯一方

我正在使用Flask+Apache+mod_wsgi构建一个web服务器。我需要在我的web服务器中启动一个后台线程,以便定期做一些事情。一切正常,应用程序启动,线程工作,但我不能加入它。以下是一些代码片段:

.wsgi文件 main.py 因此,在
app.log
中,我只看到“app start”

也许,还有其他方法可以在apache和wsgi shutdown上加入我的线程,而不仅仅是使用
atexit
模块。

看看如何在:

在mod_wsgi下,使用atexit模块是触发进程关闭操作的唯一方法。

请参见以下步骤:


在mod_wsgi下,使用
atexit
模块是触发进程关闭操作的唯一方法。

我将
atexit
处理程序放在
wsgi.py
文件中,但没有结果。在调试日志中,我看不到
应用程序现在将被关闭。我试图将此处理程序设置为
main.py
,但仍然无效。请将更新后的代码放在摘要中,以便查看您是否实际更改了它以匹配文档中的内容。你的代码的工作原理是不同的。在Apache中将LogLevel设置为into,并在进程应该关闭时收集Apache错误日志。有些事情可能会导致进程无法正常关闭,但如果您的代码有其他问题,则会导致进程被终止。我将
atexit
处理程序放在
wsgi.py
文件中,但没有产生任何结果。在调试日志中,我看不到
应用程序现在将被关闭。我试图将此处理程序设置为
main.py
,但仍然无效。请将更新后的代码放在摘要中,以便查看您是否实际更改了它以匹配文档中的内容。你的代码的工作原理是不同的。在Apache中将LogLevel设置为into,并在进程应该关闭时收集Apache错误日志。有些事情可能会导致进程无法正常关闭,但如果您的代码存在其他问题,则会导致进程被终止。
import sys, atexit, logging

logging.basicConfig(filename='app.log', level=logging.INFO, filemode='w')
logging.info('App started')

sys.path.insert(0, '/my/src/dir/with/main.py/')

from main import app, users_manager

@atexit.register
def on_exit_callback():
    logging.info('App will now be shutdowned')
    users_manager.set_shutting_down()
    users_manager.join_thread()

application = app
from flask import Flask
import logging
from threading import Thread

app = Flask(__name__)

@app.route("/", methods=['GET'])
def home():
   return "OK"

class UsersManager():
    def __init__(self):
        self.users = {}

        self.shutdown_thread = False

        self.my_worker_thread = Thread(target=self.worker_function)
        self.my_worker_thread.start()

    def worker_function(self):
        while self.shutdown_thread is not True:
            # doing my stuff

    def set_shutting_down(self):
        self.shutdown_thread = True

    def join_thread(self):
        logging.info('joining thread')
        if self.my_worker_thread.is_alive():
            logging.info('thread is alive')
            self.my_worker_thread.join()

users_manager = UsersManager()

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