Django:服务器退出时如何运行函数? [英] Django: How to run a function when server exits?
问题描述
我正在编写一个Django项目,其中使用Popen打开了多个进程。现在,当服务器退出时,这些进程将被孤立。我有一个终止这些进程的功能,并且希望对其进行组织,以便在服务器退出时自动调用此功能。
I am writing a Django project where several processes are opened using Popen. Right now, when the server exits, these processes are orphaned. I have a function to terminate these processes, and I wish to organise it so that this function is called automatically when the server quits.
任何帮助将不胜感激。
推荐答案
没有指定要使用的HTTP服务器(uWSGI,nginx,apache等),您可以在简单的开发服务器上测试此配方。
Since you haven't specified which HTTP server you are using (uWSGI, nginx, apache etc.), you can test this recipe out on a simple dev server.
可以尝试的方法通过 atexit
注册清除功能模块,将在进程终止时调用。您可以通过覆盖django内置的 runserver
命令轻松完成此操作。
What you can try is to register a cleanup function via atexit
module that will be called at process termination. You can do this easily by overriding django's builtin runserver
command.
创建一个名为 runserver.py的文件并将其放在 $ PATH_TO_YOUR_APP / management / commands /
目录中。
Create a file named runserver.py and put that in $PATH_TO_YOUR_APP/management/commands/
directory.
假设 PROCESSES_TO_KILL
是一个全局列表,其中包含对孤儿进程的引用,这些孤儿进程将在服务器终止时终止。
Assuming PROCESSES_TO_KILL
is a global list holding references to orphan processes that will be killed upon server termination.
import atexit
import signal
import sys
from django.core.management.commands.runserver import BaseRunserverCommand
class NewRunserverCommand(BaseRunserverCommand):
def __init__(self, *args, **kwargs):
atexit.register(self._exit)
signal.signal(signal.SIGINT, self._handle_SIGINT)
super(Command, self).__init__(*args, **kwargs)
def _exit(self):
for process in PROCESSES_TO_KILL:
process.terminate()
def _handle_SIGINT(signal, frame):
self._exit()
sys.exit(0)
请注意这对于正常终止脚本很有用,但是在所有情况下都不会被调用(例如致命的内部错误)。
Just be aware that this works great for normal termination of the script, but it won't get called in all cases (e.g. fatal internal errors).
希望这会有所帮助。
这篇关于Django:服务器退出时如何运行函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!