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进程时进行一些清理.
有关最佳方法的任何想法吗?
在正常终止服务器控制的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)
| 归档时间: |
|
| 查看次数: |
1684 次 |
| 最近记录: |