django settings per application - best practice?

后端 未结 4 493
忘了有多久
忘了有多久 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:56

    Since Django 1.7 there is a django-based structure for app-oriented configurations! You could find descriptive solution here

    In this new structure, conventionally you could have an apps.py file in your applications' folder which are embeded in project, something like this:

    proj/
        proj/
             settings.py
        app1/
            apps.py
            views.py
        app2/
            apps.py
            views.py
    

    app1/apps.py file could include something like this:

    from django.apps import AppConfig
    
    
    class App1Config(AppConfig):
        # typical systemic configurations
        name = 'app1'
        verbose_name = 'First App'
    
        # your desired configurations
        OPTION_A = 'default_value'
        APP_NAMESPACE = 'APP'
        APP_OPTION_B = 4
    

    you could have app2/apps.py something different like this:

    from django.apps import AppConfig
    
    
    class App2Config(AppConfig):
        # typical systemic configurations
        name = 'app2'
        verbose_name = 'Second App'
    
        # your desired configurations
        OTHER_CONFIGURATION = 'default_value'
        OPTION_C = 5
    

    and so etc for other apps.pys in you Django Application folder.

    It's important that you should import applications you included apps.py in, as follows:

    # proj/settings.py
    
    INSTALLED_APPS = [
        'app1.apps.App1Config',
        'app2.apps.App2Config',
        # ...
    ]
    

    ‌Now, You could access desired app-based configuration someway like this:

    from django.apps import apps
    apps.get_app_config('app1').OPTION_A
    

提交回复
热议问题