Correct place to put extra startup code in django?

前端 未结 7 1160
深忆病人
深忆病人 2021-01-05 09:20

I would like to run some environment checks when my django process starts and die noisily in the case of an error. I\'m thinking things like the database has an incorrect en

相关标签:
7条回答
  • 2021-01-05 09:48

    You can put it in settings.py as mentioned by others, but having code in the settings is not ideal. There is also the option of adding a handler for django.db.models.signals.class_prepared that does the desired start up checks after a specific model class is prepared.

    0 讨论(0)
  • 2021-01-05 09:54

    If you want to check that the system is correctly installed, I think that you should write your own admin command and run it as post-installation check.

    I think that it doesn't worth to check if the python version is correctly installed too often especially if you are installing the django app on shared-host. My app is hosted at alwaysdata and they restart the FastCgi process every hour. These checks can have an impact on the application response time.

    0 讨论(0)
  • 2021-01-05 09:55

    Most of the answers here are extremely old, so I assume that's why Django's checks framework isn't mentioned.

    It's been a part of django since at least v2 (django==3.1 at the time of writing).

    That's probably the right place for most of the checks you're requiring.

    I'd still consider using settings, as mentioned by other answers, for checks where settings contents are required but which also need to be run prior to readying the apps.

    0 讨论(0)
  • 2021-01-05 10:05

    We use the top-level urls.py for this.

    0 讨论(0)
  • 2021-01-05 10:06

    I would put them in settings.py. In the past, I have put system checks like this:

    try:
        from local_settings import *
    except ImportError:
        print "Missing %s" % os.path.join(PROJECT_ROOT, "local_settings.py")
    
    if DEBUG:
        for p in [PROJECT_ROOT, MEDIA_ROOT, THEME_DIR, ADMIN_MEDIA_ROOT] + list(TEMPLATE_DIRS):
            p = os.path.normpath(p)
            if not os.path.exists(p):
                print "Missing path: %s" % p
    
    0 讨论(0)
  • 2021-01-05 10:06

    If you don't want to use settings module, then try project's __init__.py.

    0 讨论(0)
提交回复
热议问题