django settings per application - best practice?

后端 未结 4 500
忘了有多久
忘了有多久 2021-02-01 12:58

this is somewhat related to this question
Why is django's settings object a LazyObject?

In my django project i have several applications. Each application can ha

4条回答
  •  不知归路
    2021-02-01 13:54

    Not sure about best practices but I don't have any problems with following style:

    proj/settings.py

    OPTION_A = 'value'
    
    # or with namespace
    APP_NAMESPACE = 'APP'
    APP_OPTION_B = 4
    

    app/settings.py

    from django.conf import settings
    from django.utils.functional import SimpleLazyObject
    
    OPTION_A = getattr(settings, 'OPTION_A', 'default_value')
    
    # or with namespace
    NAMESPACE = getattr(settings, APP_NAMESPACE, 'APP')
    OPTION_B = getattr(settings, '_'.join([NAMESPACE, 'OPTION_B']), 'default_value')
    OPTION_C = getattr(settings, '_'.join([NAMESPACE, 'OPTION_C']), None)
    if OPTION_C is None:
        raise ImproperlyConfigured('...')
    
    # lazy option with long initialization
    OPTION_D = SimpleLazyObject(lambda: open('file.txt').read())
    

    app/views.py

    from .settings import OPTION_A, OPTION_B
    # or
    from . import settings as app_settings
    app_settings.OPTION_C
    app_settings.OPTION_D  # initialized on access
    

提交回复
热议问题