Last active
December 15, 2015 07:59
-
-
Save reimund/5227124 to your computer and use it in GitHub Desktop.
Class based settings for Django. Set all common settings in BaseSettings, then create a subclass for each environment. Uses the environment variable DJANGO_ENV in order to decide which subclass it should use. I named the package "zettings" rather than "settings" to avoid import problems.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" settings.py """ | |
import sys, os | |
from zettings.base import * | |
sys.path.append(os.getcwd() + '/../') | |
ENV = os.environ.get('DJANGO_ENV', 'localdev') | |
# Import the right settings for this environment. | |
# DJANGO_ENV should be set to the name of a module which contains a | |
# BaseSettings subclass. It will look for zettings/<DJANGO_ENV>.py | |
try: | |
zettings = __import__('zettings.' + ENV, fromlist=[None]) | |
except ImportError as e: | |
print(e) | |
this_module = sys.modules[__name__] | |
# We assume settings is already defined in zettings/<DJANGO_ENV>.py. | |
for setting in dir(zettings.settings): | |
if '__' != setting[:2]: | |
setattr(this_module, setting, getattr(zettings.settings, setting)) | |
""" zettings/base.py """ | |
# | |
# Base settings used for all environments. | |
# | |
class BaseSettings(object): | |
def __init__(self, options): | |
# Some settings must be set by the subclass. | |
WEBSITE_ROOT = options['WEBSITE_ROOT'] | |
HOST_NAME = options['HOST_NAME'] | |
MEDIA_HOST_NAME = options['MEDIA_HOST_NAME'] | |
# The rest of the base settings goes here | |
MEDIA_URL = ... | |
self.set_locals(locals()) | |
# Put local variables in instance scope. | |
# We do this so we don't have to write "self." for every Django setting. | |
def set_locals(self, vars): | |
for var, value in vars.iteritems(): | |
setattr(self, var, value) | |
""" zettings/hackmon.py """ | |
from base import BaseSettings | |
# | |
# Hackmon specific settings. | |
# | |
class HackmonSettings(BaseSettings): | |
def __init__(self, options): | |
BaseSettings.__init__(self, options) | |
DEBUG = True | |
TEMPLATE_DEBUG = True | |
DATABASES = { | |
... | |
} | |
self.set_locals(locals()) | |
# These are used by BaseSettings. | |
settings = HackmonSettings( | |
{ | |
'WEBSITE_ROOT': '...', | |
'HOST_NAME': '...', | |
'MEDIA_HOST_NAME': '...', | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment