Elegantly handle site-specific settings/configuration in svn/hg/git/etc?

后端 未结 4 1146
小蘑菇
小蘑菇 2020-12-14 16:30

I\'ve been looking for a better way to deal with site-specific settings (in this case, the django settings.py file).

The settings.py structure and fields are fairly

4条回答
  •  死守一世寂寞
    2020-12-14 17:11

    Create a main settings.py file, which should include this:

    # Pull in hostname-based changes.
    import socket
    HOSTNAME = socket.gethostname().lower().split('.')[0].replace('-','')
    
    try:
        exec "from myproject.settings.host_%s import *" % HOSTNAME
    except ImportError:
        pass
    
    # Pull in the local changes.
    try:
        from myproject.settings.local import *
    except ImportError:
        pass
    

    Now you create a new settings file for each host name you care about. But these are really small. Each of your production server's file just contains:

    from myproject.settings.production import *
    

    and your staging servers have:

    from myproject.settings.staging import *
    

    Now you can create a production.py file with production overrides for settings, a staging.py, and so on. You can make new files for each role a server plays.

    Finally, you can create a local.py file on any machine (including developers' machines) with local overrides, and mark this file as ignored by source control, so that changes don't get checked in.

    We've used this structure for years, it works really well.

提交回复
热议问题