Skip to content

Instantly share code, notes, and snippets.

@thedrow
Created March 13, 2013 16:25
Show Gist options
  • Save thedrow/5153782 to your computer and use it in GitHub Desktop.
Save thedrow/5153782 to your computer and use it in GitHub Desktop.
The working settings.py prototype that allows you to load packages and modules as settings.
def monkey_patch():
"""
Monkeypatches
"""
import logging
import pkgutil
import warnings
import os
from django.core.exceptions import ImproperlyConfigured
from django.utils import importlib, six
from django.utils.functional import empty, LazyObject
import time
from django import conf
class Settings(conf.BaseSettings):
def __init__(self, settings_module):
# update this dict from global settings (but only for ALL_CAPS settings)
for setting in dir(conf.global_settings):
if setting == setting.upper():
setattr(self, setting, getattr(conf.global_settings, setting))
# store the settings module in case someone later cares
self.SETTINGS_MODULE = settings_module
try:
module = importlib.import_module(self.SETTINGS_MODULE)
except ImportError as e:
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
if module.__package__:
deployments_module_name = module.__package__.rsplit('.', 1)[0]
try:
common_settings_module = importlib.import_module('.common.settings', deployments_module_name)
except ImportError:
common_settings_module = None
common_settings_module_name = '%s.common.settings' % deployments_module_name
else:
deployments_module_name = module.__name__.rsplit(sep='.', maxsplit=1)[0]
try:
common_settings_module = importlib.import_module('.common.settings', deployments_module_name)
except ImportError:
common_settings_module = None
common_settings_module_name = '%s.common.settings' % deployments_module_name
if common_settings_module:
self.collect(common_settings_module, common_settings_module_name)
self.collect(module, self.SETTINGS_MODULE)
if not self.SECRET_KEY:
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
if hasattr(time, 'tzset') and self.TIME_ZONE:
# When we can, attempt to validate the timezone. If we can't find
# this file, no check happens and it's harmless.
zoneinfo_root = '/usr/share/zoneinfo'
if (os.path.exists(zoneinfo_root) and not
os.path.exists(os.path.join(zoneinfo_root, *(self.TIME_ZONE.split('/'))))):
raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
# Move the time zone info into os.environ. See ticket #2315 for why
# we don't do this unconditionally (breaks Windows).
os.environ['TZ'] = self.TIME_ZONE
time.tzset()
def collect_settings(self, module):
# Settings that should be converted into tuples if they're mistakenly entered
# as strings.
tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS")
for setting in dir(module):
if setting == setting.upper():
setting_value = getattr(module, setting)
if setting in tuple_settings and \
isinstance(setting_value, six.string_types):
warnings.warn("The %s setting must be a tuple. Please fix your "
"settings, as auto-correction is now deprecated." % setting,
PendingDeprecationWarning)
setting_value = (setting_value,) # In case the user forgot the comma.
if setting.startswith('ADDITIONAL_'):
setting_name = setting.split('ADDITIONAL_', 1)[1]
current_value = getattr(self, setting_name)
setting_value += current_value
setattr(self, setting_name, setting_value)
else:
setattr(self, setting, setting_value)
def collect_settings_modules(self, settings_module_path, settings_module):
modules = [importlib.import_module('.%s' % module, settings_module) for _, module, is_package in
pkgutil.iter_modules(settings_module_path)]
for module in modules:
self.collect_settings(module)
def collect(self, module, settings_module):
if not module.__package__:
settings_module_path = module.__path__
self.collect_settings_modules(settings_module_path, settings_module)
else:
self.collect_settings(module)
class LazySettings(LazyObject):
"""
A lazy proxy for either global Django settings or a custom settings object.
The user can manually configure settings prior to using them. Otherwise,
Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE.
"""
def _setup(self, name=None):
"""
Load the settings module pointed to by the environment variable. This
is used the first time we need any settings at all, if the user has not
previously configured the settings manually.
"""
try:
settings_module = os.environ[conf.ENVIRONMENT_VARIABLE]
if not settings_module: # If it's set but is an empty string.
raise KeyError
except KeyError:
desc = ("setting %s" % name) if name else "settings"
raise ImproperlyConfigured(
"Requested %s, but settings are not configured. "
"You must either define the environment variable %s "
"or call settings.configure() before accessing settings."
% (desc, conf.ENVIRONMENT_VARIABLE))
self._wrapped = Settings(settings_module)
self._configure_logging()
def __getattr__(self, name):
if self._wrapped is empty:
self._setup(name)
return getattr(self._wrapped, name)
def _configure_logging(self):
"""
Setup logging from LOGGING_CONFIG and LOGGING settings.
"""
try:
# Route warnings through python logging
logging.captureWarnings(True)
# Allow DeprecationWarnings through the warnings filters
warnings.simplefilter("default", DeprecationWarning)
except AttributeError:
# No captureWarnings on Python 2.6, DeprecationWarnings are on anyway
pass
if self.LOGGING_CONFIG:
from django.utils.log import DEFAULT_LOGGING
# First find the logging configuration function ...
logging_config_path, logging_config_func_name = self.LOGGING_CONFIG.rsplit('.', 1)
logging_config_module = importlib.import_module(logging_config_path)
logging_config_func = getattr(logging_config_module, logging_config_func_name)
logging_config_func(DEFAULT_LOGGING)
if self.LOGGING:
# Backwards-compatibility shim for #16288 fix
conf.compat_patch_logging_config(self.LOGGING)
# ... then invoke it with the logging settings
logging_config_func(self.LOGGING)
def configure(self, default_settings=conf.global_settings, **options):
"""
Called to manually configure the settings. The 'default_settings'
parameter sets where to retrieve any unspecified values from (its
argument must support attribute access (__getattr__)).
"""
if self._wrapped is not empty:
raise RuntimeError('Settings already configured.')
holder = conf.UserSettingsHolder(default_settings)
for name, value in options.items():
setattr(holder, name, value)
self._wrapped = holder
self._configure_logging()
@property
def configured(self):
"""
Returns True if the settings have already been configured.
"""
return self._wrapped is not empty
conf.settings = LazySettings()
globals().update({'conf': conf})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment