Skip to content

Instantly share code, notes, and snippets.

@thedrow
Last active December 15, 2015 01:29
Show Gist options
  • Select an option

  • Save thedrow/5180120 to your computer and use it in GitHub Desktop.

Select an option

Save thedrow/5180120 to your computer and use it in GitHub Desktop.
django-configurations implementation in 5 minutes. This loads settings from a class instead of a module. To use it just clone https://github.com/thedrow/django/ and set the DJANGO_CONFIGURATION environment variable to whichever object you'd like to use and import this settings module instead of django.conf.settings. The class shouldn't inherit f…
"""
Demonstrates loading settings from a module and overriding it by a class
"""
import os
from django.utils import importlib
from django.conf.default import *
class ConfigurationLoader(SettingsSourcesLoader):
CONFIGURATION_ENVIRONMENT_VARIABLE = "DJANGO_CONFIGURATION"
def load(self):
sources = super(ConfigurationLoader, self).load()
sources.extend([self._import_configuration(os.environ[self.CONFIGURATION_ENVIRONMENT_VARIABLE])])
return sources
def _import_configuration(self, configuration):
try:
module_and_config = configuration.rsplit('.', 1)
return getattr(importlib.import_module(module_and_config[0]), module_and_config[1])
except ImportError as e:
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (configuration, e))
def get_error_message(self, setting_name, *args, **kwargs):
desc = ("setting %s" % setting_name) if setting_name else "settings"
return """Requested %s, but settings are not configured.
You must either define the environment variable %s
or call settings.configure() before accessing settings.""" % (
desc, self.CONFIGURATION_ENVIRONMENT_VARIABLE)
settings = LazySettings(settings_sources_loader=ConfigurationLoader)
"""
Demonstrates loading settings from a class
"""
import os
from django.utils import importlib
from django.conf.default import *
class ConfigurationLoader(BaseSettingsSourcesLoader):
ENVIRONMENT_VARIABLE = "DJANGO_CONFIGURATION"
def load(self):
return [global_settings, self._import_configuration(os.environ[self.ENVIRONMENT_VARIABLE])]
def _import_configuration(self, configuration):
try:
module_and_config = configuration.rsplit('.', 1)
return getattr(importlib.import_module(module_and_config[0]), module_and_config[1])
except ImportError as e:
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (configuration, e))
def get_error_message(self, setting_name, *args, **kwargs):
desc = ("setting %s" % setting_name) if setting_name else "settings"
return """Requested %s, but settings are not configured.
You must either define the environment variable %s
or call settings.configure() before accessing settings.""" % (
desc, self.ENVIRONMENT_VARIABLE)
settings = LazySettings(settings_sources_loader=ConfigurationLoader)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment