我有一个在 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')
当子进程被杀死/结束/终止时,我希望 Flask 应用程序删除这个文件。
删除文件并不是特别重要,因为这些文件不会占用太多空间,所以如果出现奇怪的错误我不需要处理它们。但是对于正常的工作流程,我希望在 Apache 关闭 Flask 进程时进行一些清理。
关于执行此操作的最佳方法有什么想法吗?
最佳答案
在正常终止服务器控制的 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)
关于python - Apache 终止 Flask 进程时如何调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29756852/