Execute code when Django starts ONCE only?

前端 未结 7 1391
终归单人心
终归单人心 2020-11-22 13:55

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

7条回答
  •  忘了有多久
    2020-11-22 14:36

    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.

提交回复
热议问题