python - Django: How to run a function when server exits? -
i writing django project several processes opened using popen. right now, when server exits, these processes orphaned. have function terminate these processes, , wish organise function called automatically when server quits.
any appreciated.
since haven't specified http server using (uwsgi, nginx, apache etc.), can test recipe out on simple dev server.
what can try register cleanup function via atexit
module called @ process termination. can overriding django's builtin runserver
command.
create file named runserver.py , put in $path_to_your_app/management/commands/
directory.
assuming processes_to_kill
global list holding references orphan processes killed upon server termination.
import atexit import signal import sys 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): process in processes_to_kill: process.terminate() def _handle_sigint(signal, frame): self._exit() sys.exit(0)
just aware works great normal termination of script, won't called in cases (e.g. fatal internal errors).
hope helps.
Comments
Post a Comment