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
file: myapp/apps.py
from django.apps import AppConfig
class MyAppConfig(AppConfig):
name = 'myapp'
verbose_name = "My Application"
def ready(self):
pass # startup code here
file: myapp/__init__.py
default_app_config = 'myapp.apps.MyAppConfig'
The number one answer does not seem to work anymore, urls.py is loaded upon first request.
What has worked lately is to put the startup code in any one of your INSTALLED_APPS init.py e.g. myapp/__init__.py
def startup():
pass # load a big thing
startup()
When using ./manage.py runserver
... this gets executed twice, but that is because runserver has some tricks to validate the models first etc ... normal deployments or even when runserver auto reloads, this is only executed once.