Execute code when Django starts ONCE only?

前端 未结 7 1383
终归单人心
终归单人心 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:46

    As suggested by @Pykler, in Django 1.7+ you should use the hook explained in his answer, but if you want that your function is called only when run server is called (and not when making migrations, migrate, shell, etc. are called), and you want to avoid AppRegistryNotReady exceptions you have to do as follows:

    file: myapp/apps.py

    import sys
    from django.apps import AppConfig
    
    class MyAppConfig(AppConfig):
        name = 'my_app'
    
        def ready(self):
            if 'runserver' not in sys.argv:
                return True
            # you must import your modules here 
            # to avoid AppRegistryNotReady exception 
            from .models import MyModel 
            # startup code here
    
    0 讨论(0)
提交回复
热议问题