【问题标题】:I can't join background thread in flask with apache's mod_wsgi我无法使用 apache 的 mod_wsgi 加入烧瓶中的后台线程
【发布时间】:2016-04-13 09:25:56
【问题描述】:

我正在使用 Flask + Apache + mod_wsgi 构建一个网络服务器。我需要在我的网络服务器中启动一个后台线程,以便定期做一些事情。一切都很好,应用程序已启动并且线程可以正常工作,但我无法加入它。下面是一些代码sn-ps:

.wsgi 文件

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

main.py

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()

所以,在 app.log 中,我只看到“应用已启动”。

也许,除了使用atexit 模块之外,还有其他方法可以在 apache 和 wsgi 关闭时加入我的线程。

【问题讨论】:

    标签: python multithreading apache flask mod-wsgi


    【解决方案1】:

    看看它是如何完成的:

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

    【讨论】:

    • 我将atexit 处理程序放到wsgi.py 文件中,但它没有带来任何结果。我在调试日志中没有看到App will now be shutdowned。我试图把这个处理程序放到main.py - 仍然没有效果。
    • 将您更新的代码放在一个要点中,以便查看您是否真的更改了它以匹配记录的内容。您的代码的工作方式不一样。还要在 Apache 中将 LogLevel 设置为 into,并在进程应该关闭时收集 Apache 错误日志。有些事情可能会导致进程无法正常关闭,但如果您的代码有其他问题,则只会被杀死。
    最近更新 更多