Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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 consistent, but the values differ between the developer's boxes, the integration, QA, testing, and production environments.

What's an elegant way to have the settings source controlled while still allowing changes between different boxes?

I'm also concerned about having sensitive data (eg. database passwords) in source control, but I do want automated deployments.

Examples of what we've used:

  • settings.py sets the common values then loads a secondary settings file based on the hostname or the username .

  • injecting values into the settings.py file using a deployment script. But this simply shifts the problem to managing the deployment scripts instead of the settings.py script.

Anyone have a particularly elegant approach?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...