Skip to content

Instantly share code, notes, and snippets.

@ydm
Created July 7, 2014 09:39
Show Gist options
  • Save ydm/398fe645b54c9996d2bb to your computer and use it in GitHub Desktop.
Save ydm/398fe645b54c9996d2bb to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
import importlib
import os
class ImproperlyConfigured(Exception):
pass
SETTINGS_MODULE_VAR = 'PROJECT_SETTINGS_MODULE'
VARIABLE_CATALOG_VAR = 'PROJECT_VARIABLE_CATALOG'
class VariableCatalog(object):
def __init__(self, variables_catalog):
self.variables = {}
if os.path.exists(variables_catalog):
for var in os.listdir(variables_catalog):
fpath = os.path.join(variables_catalog, var)
if os.path.isfile(fpath):
with open(fpath) as f:
self.variables[var] = f.read().strip()
def __getattr__(self, name):
try:
return self.variables[name]
except KeyError as e:
raise AttributeError(e)
class Settings(object):
# Default settings
DEBUG = 1
def __init__(self, settings_module, pre=None, post=None):
self.pre = pre or []
self.post = post or []
self.mod = importlib.import_module(settings_module)
def __getattr__(self, name):
for obj in self.pre:
try:
return getattr(obj, name)
except AttributeError:
pass
try:
return getattr(self.mod, name)
except AttributeError:
pass
for obj in self.post:
try:
return getattr(obj, name)
except AttributeError:
pass
raise AttributeError
pre = []
settings_module = os.environ.get(SETTINGS_MODULE_VAR)
variable_catalog = os.environ.get(VARIABLE_CATALOG_VAR)
if not settings_module:
raise ImproperlyConfigured(
'You need to set the {} env variable'.format(
SETTINGS_MODULE_VAR
)
)
if variable_catalog:
pre.append(VariableCatalog(variable_catalog))
settings = Settings(settings_module, pre=pre)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment