I want to run some code when my Django server starts-up in order to clean up from the previous end of the server. How can I run some code once and only once at startup before the server processes any requests. I need to access the database during this time.
I've read a couple of things online that seem a bit outdated and are also not guaranteed to run only once.
Update
I've looked at the suggested answer by looking into the ready
function. That appears to work, but it is documented that you should not access the database there (https://docs.djangoproject.com/en/dev/ref/applications/#django.apps.AppConfig.ready)
There are many suggestions at Execute code when Django starts ONCE only?, but since that post is a few years old, I thought there might be some additional solutions.
This looks promising
from django.dispatch import receiver
from django.db.backends.signals import connection_created
@receiver(connection_created)
def my_receiver(connection, **kwargs):
with connection.cursor() as cursor:
# do something to the database
connection_created.disconnect(my_receiver)
Any other thoughts?