Different approach to local settings.py

February 15, 2008
settings development deployment
6 (after 6 ratings)

I like to keep all local settings files in my versioning repository. The way I differentiate between them is by querying the hostname of the local machine. I've got a host_settings folder with local settings files. Notice that the local settings file names go by a convention where '.' is replaced with underscores.

Example: host_settings/local_machine_tld.py

    import socket
    hostname = socket.gethostname().replace('.','_')
    exec "from host_settings.%s import *" % hostname
except ImportError, e:
    raise e

More like this

  1. Read settings from local_settings.py by statico 6 years, 7 months ago
  2. Django Settings Splitter & Local Settings loader by rudude 2 years, 5 months ago
  3. manage.py with magic python path by bikeshedder 9 years, 2 months ago
  4. currency filter without using locale by andzep 5 years, 6 months ago
  5. invoke pyflakes via manage.py by mpasternacki 6 years, 10 months ago


whiskybar (on February 15, 2008):
<p>Very useful indeed. I use a similar approach:</p> <p>settings.py:</p> <pre>import socket hostname = socket.gethostname() if hostname == 'apples': DATABASE_NAME = 'juice' DATABASE_USER etc. elif hostname == 'pears': etc. etc. </pre> <p>I have a question though. Somebody told me this may not work in Mac or Windows. Have you tried that?</p>


jokull (on February 15, 2008):
<p>I haven't tried it out on Windows but OSX correctly returns the hostname.</p>


itavor (on February 17, 2008):
<p>Wow, what a great idea!</p> <p>More code, shorter filenames:</p> <pre>import socket hostname = socket.gethostname().split('.') while True: try: exec 'from host_settings.%s import *' % '_'.join(hostname) break except ImportError: hostname = hostname[:-1] </pre>


luftyluft (on February 17, 2008):
<p>Use of "exec" will scare some users away from this snippet. There may be valid use cases for exec, but many Python programmers IMHO avoid the use of it like the plague. Kind of like a goto statement in a C program - it's just not done :)</p> <p>Using the built-in _import_ might be the way to go.</p>


jokull (on February 23, 2008):
<p>I tried to do something with import but it doesn't seem to support the from x import * syntax. Am I wrong?</p>


buriy (on February 24, 2008):
<p>working well on windows.</p> <p>i'd like to change snippet a bit:</p> <pre>try: import socket hostname = socket.gethostname().replace('.','_') __import__("settings_%s" % hostname) except ImportError, e: import sys sys.stderr.write('Unable to read settings_%s.py\n' % hostname) sys.exit(1) </pre>


buriy (on February 25, 2008):
<p>oops, guys, you're right. i have to read how to do "from ... import *" with import.</p>


Please login first before commenting.