Execute code when Django starts ONCE only?

Update: Django 1.7 now has a hook for this

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'

For Django < 1.7

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.

Leave a Comment