Django: How to run a function when the server exits?

I am writing a Django project where several processes are opened using Popen. Right now, when the server is shutting down, these processes are becoming orphans. I have a function to complete these processes, and I want to arrange it so that this function is called automatically when the server shuts down.

Any help would be greatly appreciated.

+4
source share
2 answers

Since you did not specify which HTTP server you are using (uWSGI, nginx, apache, etc.), you can test this recipe on a simple dev server.

- atexit , . , django builtin runserver.

runningerver.py $PATH_TO_YOUR_APP/management/commands/.

, PROCESSES_TO_KILL - , , .

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)

, script, (, ).

, .

+3

, " ", . ? ?

, - , -, , , , .

, , , Middleware. , - process_response.

, , , , - , Celery .

0

Source: https://habr.com/ru/post/1584640/


All Articles