[Django]-Django Framework – Is there a shutdown event that can be subscribed to?

19👍

I don’t know of a shutdown event, but you can create one.

When the user presses Ctrl-C, a SIGINT signal is sent to Python process. Setup a signal handler from your wsgi.py file to catch the SIGINT and forward it to your program.

wsgi.py:

...

import signal
signal.signal(signal.SIGINT, my_signal_handler)

You could even forward the signal to a django signal:

my_django_shutdown_signal = django.dispatch.Signal()

def _forward_to_django_shutdown_signal(signal, frame):
    my_django_shutdown_signal.send('system')
    sys.exit(0)   # So runserver does try to exit
signal.signal(signal.SIGINT, _forward_to_django_shutdown_signal)

Since signal can only be called from the main thread, this won’t work with runserver. Either call runserver with the --noreload option, or switch over to gunicorn.

5👍

Addition to answer by Stu Gla:
To set handler for signal event in main thread in django you can put put initialization of handling to manage.py or your app’s __init__.py, like so:

#  {project_root}/{your_app}/__init__.py
import os  
import signal  
import sys  
def my_signal_handler(*args):  
    if os.environ.get('RUN_MAIN') == 'true':  
        print('stopped'.upper())  
    sys.exit(0) 

signal.signal(signal.SIGINT, my_signal_handler)  

It will let you run server without –noreload.
Check for os.environ.get('RUN_MAIN') pvevent calling function 2 times.

Leave a comment