Apache终止Flask进程时如何调用函数?

ste*_*eve 8 python apache termination flask

我有一个在Apache HTTPD后面运行的Flask应用程序.Apache配置为具有多个子进程.

Flask应用程序在服务器上创建一个文件,其文件名称等于其进程ID.代码看起来像这样:

import os

@app.before_first_request
def before_first_request():
    filename = os.getpid()
    with open(filename, 'w') as file:
        file.write('Hello')
Run Code Online (Sandbox Code Playgroud)

当子进程被终止/结束/终止时,我希望Flask应用程序删除此文件.

删除文件并不是非常重要,因为这些文件不会占用太多空间,因此如果发生奇怪的错误,我不需要处理它们.但是对于正常的工作流程,我希望在Apache关闭Flask进程时进行一些清理.

有关最佳方法的任何想法吗?

Vel*_*ker 9

在正常终止服务器控制的Python进程(例如在Apache WSGI上下文中运行的Flask应用程序,甚至更好,在Apache后面的Gunicorn中)之前添加清除功能的最佳方法是使用atexit退出处理程序.

详细说明原始示例,这里添加了退出处理程序来执行.pid文件清理:

import atexit
import os

filename = '{}.pid'.format(os.getpid())

@app.before_first_request
def before_first_request():
    with open(filename, 'w') as file:
        file.write('Hello')

def cleanup():
    try:
        os.remove(filename)
    except Exception:
        pass

atexit.register(cleanup)
Run Code Online (Sandbox Code Playgroud)

  • Apache/mod_wsgi 当然总是尝试确保调用 atexit 回调,即使在由于请求超时等情况而必须关闭进程的情况下也是如此。在gunicorn 中没有那么好的保证,您必须在gunicorn下使用atexit要小心得多,因为在各种情况下它不会被调用。在任何一种情况下,您都不应该依赖它,并且应用程序应该能够恢复后续运行中存在的文件(如果该文件不应该存在的话)。正如其他答案所述,可能需要一个单独的任务来删除它。 (2认同)