I\'m writing a Django Middleware class that I want to execute only once at startup, to initialise some other arbritary code. I\'ve followed the very nice solution posted by
Note that you cannot reliability connect to the database or interact with models inside the AppConfig.ready function (see the warning in the docs).
If you need to interact with the database in your start-up code, one possibility is to use the connection_created signal to execute initialization code upon connection to the database.
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
Obviously, this solution is for running code once per database connection, not once per project start. So you'll want a sensible value for the CONN_MAX_AGE setting so you aren't re-running the initialization code on every request. Also note that the development server ignores CONN_MAX_AGE, so you WILL run the code once per request in development.
99% of the time this is a bad idea - database initialization code should go in migrations - but there are some use cases where you can't avoid late initialization and the caveats above are acceptable.