How to manage local vs production settings in Django?

前端 未结 22 2084
别跟我提以往
别跟我提以往 2020-11-22 15:00

What is the recommended way of handling settings for local development and the production server? Some of them (like constants, etc) can be changed/accessed in both, but s

22条回答
  •  生来不讨喜
    2020-11-22 15:23

    Instead of settings.py, use this layout:

    .
    └── settings/
        ├── __init__.py  <= not versioned
        ├── common.py
        ├── dev.py
        └── prod.py
    

    common.py is where most of your configuration lives.

    prod.py imports everything from common, and overrides whatever it needs to override:

    from __future__ import absolute_import # optional, but I like it
    from .common import *
    
    # Production overrides
    DEBUG = False
    #...
    

    Similarly, dev.py imports everything from common.py and overrides whatever it needs to override.

    Finally, __init__.py is where you decide which settings to load, and it's also where you store secrets (therefore this file should not be versioned):

    from __future__ import absolute_import
    from .prod import *  # or .dev if you want dev
    
    ##### DJANGO SECRETS
    SECRET_KEY = '(3gd6shenud@&57...'
    DATABASES['default']['PASSWORD'] = 'f9kGH...'
    
    ##### OTHER SECRETS
    AWS_SECRET_ACCESS_KEY = "h50fH..."
    

    What I like about this solution is:

    1. Everything is in your versioning system, except secrets
    2. Most configuration is in one place: common.py.
    3. Prod-specific things go in prod.py, dev-specific things go in dev.py. It's simple.
    4. You can override stuff from common.py in prod.py or dev.py, and you can override anything in __init__.py.
    5. It's straightforward python. No re-import hacks.

提交回复
热议问题