how to modularize django settings.py?

后端 未结 8 723
礼貌的吻别
礼貌的吻别 2020-12-13 19:46

When you install a new django application, you have to add/modify your settings.py module.

For a project I\'m trying to make that module a python subpackage and crea

相关标签:
8条回答
  • 2020-12-13 20:07

    I have the same structure of settings files and I do the following to import the settings of the submodules:

    def load_settings_file(file):
        file = open(os.path.join(INSTALL_DIR, '<projectname>', 'settings', file + '.py'))
        content = file.read()
        file.close()
        return content
    
    for submodule in ['base', 'admin', 'feincms']:
        exec(load_settings_file(submodule))
    
    0 讨论(0)
  • 2020-12-13 20:18

    I created https://code.djangoproject.com/wiki/SplitSettings#SettingInheritancewithHierarchy as my preferred solution. Allows for inheritance from a common file in any deployment environment.

    0 讨论(0)
  • 2020-12-13 20:20

    You might be interested in this solution; uses execfile() to load a series of settings files in order, where each file has full access to settings from previously-loaded files, to update, modify, etc.

    0 讨论(0)
  • 2020-12-13 20:20

    just put

    from base import *
    from admin import *
    ...
    

    in ur init.py that should work

    i used it for different sites

    base/settings.py # common settings: db, apps, ...
    base/sites/website1/settings.py # site_id, custom middleware 
    base/sites/website2/settings.py # site_id, custom middleware
    

    the website settings import the common settings with

    from base.settings import *
    

    and define custom attribtues

    0 讨论(0)
  • 2020-12-13 20:21

    I've used this work-around:

    settings.py:

    INSTALLED_APPS = ('whatever',)
    import more_settings
    more_settings.modify(globals())
    

    more_settings.py:

    def modify(settings):
        settings['INSTALLED_APPS'] += ('another_app',)
    
    0 讨论(0)
  • 2020-12-13 20:21

    If you prefer more magic than in my previous more_settings.modify() approach, try this:

    settings.py:

    INSTALLED_APPS = ('whatever',)
    import more_settings
    more_settings.modify(globals())
    

    more_settings.py:

    def config(INSTALLED_APPS=(), **other_settings):
        INSTALLED_APPS += ('another_app',)
        del other_settings
        return locals()
    
    def modify(settings):
        settings.update(config(**settings))
    

    Pros: no need to refer to settings with dict notation

    Cons: must define modified settings as kwargs for config()

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