PageRenderTime 38ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/django-1.5/django/conf/__init__.py

https://github.com/theosp/google_appengine
Python | 233 lines | 158 code | 31 blank | 44 comment | 22 complexity | e8771cf3704fed53c3e345d2b5eade56 MD5 | raw file
  1. """
  2. Settings and configuration for Django.
  3. Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment
  4. variable, and then from django.conf.global_settings; see the global settings file for
  5. a list of all possible variables.
  6. """
  7. import logging
  8. import os
  9. import sys
  10. import time # Needed for Windows
  11. import warnings
  12. from django.conf import global_settings
  13. from django.core.exceptions import ImproperlyConfigured
  14. from django.utils.functional import LazyObject, empty
  15. from django.utils import importlib
  16. from django.utils import six
  17. ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE"
  18. class LazySettings(LazyObject):
  19. """
  20. A lazy proxy for either global Django settings or a custom settings object.
  21. The user can manually configure settings prior to using them. Otherwise,
  22. Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE.
  23. """
  24. def _setup(self, name=None):
  25. """
  26. Load the settings module pointed to by the environment variable. This
  27. is used the first time we need any settings at all, if the user has not
  28. previously configured the settings manually.
  29. """
  30. try:
  31. settings_module = os.environ[ENVIRONMENT_VARIABLE]
  32. if not settings_module: # If it's set but is an empty string.
  33. raise KeyError
  34. except KeyError:
  35. desc = ("setting %s" % name) if name else "settings"
  36. raise ImproperlyConfigured(
  37. "Requested %s, but settings are not configured. "
  38. "You must either define the environment variable %s "
  39. "or call settings.configure() before accessing settings."
  40. % (desc, ENVIRONMENT_VARIABLE))
  41. self._wrapped = Settings(settings_module)
  42. self._configure_logging()
  43. def __getattr__(self, name):
  44. if self._wrapped is empty:
  45. self._setup(name)
  46. return getattr(self._wrapped, name)
  47. def _configure_logging(self):
  48. """
  49. Setup logging from LOGGING_CONFIG and LOGGING settings.
  50. """
  51. if not sys.warnoptions:
  52. try:
  53. # Route warnings through python logging
  54. logging.captureWarnings(True)
  55. # Allow DeprecationWarnings through the warnings filters
  56. warnings.simplefilter("default", DeprecationWarning)
  57. except AttributeError:
  58. # No captureWarnings on Python 2.6, DeprecationWarnings are on anyway
  59. pass
  60. if self.LOGGING_CONFIG:
  61. from django.utils.log import DEFAULT_LOGGING
  62. # First find the logging configuration function ...
  63. logging_config_path, logging_config_func_name = self.LOGGING_CONFIG.rsplit('.', 1)
  64. logging_config_module = importlib.import_module(logging_config_path)
  65. logging_config_func = getattr(logging_config_module, logging_config_func_name)
  66. logging_config_func(DEFAULT_LOGGING)
  67. if self.LOGGING:
  68. # Backwards-compatibility shim for #16288 fix
  69. compat_patch_logging_config(self.LOGGING)
  70. # ... then invoke it with the logging settings
  71. logging_config_func(self.LOGGING)
  72. def configure(self, default_settings=global_settings, **options):
  73. """
  74. Called to manually configure the settings. The 'default_settings'
  75. parameter sets where to retrieve any unspecified values from (its
  76. argument must support attribute access (__getattr__)).
  77. """
  78. if self._wrapped is not empty:
  79. raise RuntimeError('Settings already configured.')
  80. holder = UserSettingsHolder(default_settings)
  81. for name, value in options.items():
  82. setattr(holder, name, value)
  83. self._wrapped = holder
  84. self._configure_logging()
  85. @property
  86. def configured(self):
  87. """
  88. Returns True if the settings have already been configured.
  89. """
  90. return self._wrapped is not empty
  91. class BaseSettings(object):
  92. """
  93. Common logic for settings whether set by a module or by the user.
  94. """
  95. def __setattr__(self, name, value):
  96. if name in ("MEDIA_URL", "STATIC_URL") and value and not value.endswith('/'):
  97. raise ImproperlyConfigured("If set, %s must end with a slash" % name)
  98. elif name == "ALLOWED_INCLUDE_ROOTS" and isinstance(value, six.string_types):
  99. raise ValueError("The ALLOWED_INCLUDE_ROOTS setting must be set "
  100. "to a tuple, not a string.")
  101. object.__setattr__(self, name, value)
  102. class Settings(BaseSettings):
  103. def __init__(self, settings_module):
  104. # update this dict from global settings (but only for ALL_CAPS settings)
  105. for setting in dir(global_settings):
  106. if setting == setting.upper():
  107. setattr(self, setting, getattr(global_settings, setting))
  108. # store the settings module in case someone later cares
  109. self.SETTINGS_MODULE = settings_module
  110. try:
  111. mod = importlib.import_module(self.SETTINGS_MODULE)
  112. except ImportError as e:
  113. raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
  114. # Settings that should be converted into tuples if they're mistakenly entered
  115. # as strings.
  116. tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS")
  117. for setting in dir(mod):
  118. if setting == setting.upper():
  119. setting_value = getattr(mod, setting)
  120. if setting in tuple_settings and \
  121. isinstance(setting_value, six.string_types):
  122. warnings.warn("The %s setting must be a tuple. Please fix your "
  123. "settings, as auto-correction is now deprecated." % setting,
  124. PendingDeprecationWarning)
  125. setting_value = (setting_value,) # In case the user forgot the comma.
  126. setattr(self, setting, setting_value)
  127. if not self.SECRET_KEY:
  128. raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
  129. if hasattr(time, 'tzset') and self.TIME_ZONE:
  130. # When we can, attempt to validate the timezone. If we can't find
  131. # this file, no check happens and it's harmless.
  132. zoneinfo_root = '/usr/share/zoneinfo'
  133. if (os.path.exists(zoneinfo_root) and not
  134. os.path.exists(os.path.join(zoneinfo_root, *(self.TIME_ZONE.split('/'))))):
  135. raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
  136. # Move the time zone info into os.environ. See ticket #2315 for why
  137. # we don't do this unconditionally (breaks Windows).
  138. os.environ['TZ'] = self.TIME_ZONE
  139. time.tzset()
  140. class UserSettingsHolder(BaseSettings):
  141. """
  142. Holder for user configured settings.
  143. """
  144. # SETTINGS_MODULE doesn't make much sense in the manually configured
  145. # (standalone) case.
  146. SETTINGS_MODULE = None
  147. def __init__(self, default_settings):
  148. """
  149. Requests for configuration variables not in this class are satisfied
  150. from the module specified in default_settings (if possible).
  151. """
  152. self.__dict__['_deleted'] = set()
  153. self.default_settings = default_settings
  154. def __getattr__(self, name):
  155. if name in self._deleted:
  156. raise AttributeError
  157. return getattr(self.default_settings, name)
  158. def __setattr__(self, name, value):
  159. self._deleted.discard(name)
  160. return super(UserSettingsHolder, self).__setattr__(name, value)
  161. def __delattr__(self, name):
  162. self._deleted.add(name)
  163. return super(UserSettingsHolder, self).__delattr__(name)
  164. def __dir__(self):
  165. return list(self.__dict__) + dir(self.default_settings)
  166. settings = LazySettings()
  167. def compat_patch_logging_config(logging_config):
  168. """
  169. Backwards-compatibility shim for #16288 fix. Takes initial value of
  170. ``LOGGING`` setting and patches it in-place (issuing deprecation warning)
  171. if "mail_admins" logging handler is configured but has no filters.
  172. """
  173. # Shim only if LOGGING["handlers"]["mail_admins"] exists,
  174. # but has no "filters" key
  175. if "filters" not in logging_config.get(
  176. "handlers", {}).get(
  177. "mail_admins", {"filters": []}):
  178. warnings.warn(
  179. "You have no filters defined on the 'mail_admins' logging "
  180. "handler: adding implicit debug-false-only filter. "
  181. "See http://docs.djangoproject.com/en/dev/releases/1.4/"
  182. "#request-exceptions-are-now-always-logged",
  183. DeprecationWarning)
  184. filter_name = "require_debug_false"
  185. filters = logging_config.setdefault("filters", {})
  186. while filter_name in filters:
  187. filter_name = filter_name + "_"
  188. filters[filter_name] = {
  189. "()": "django.utils.log.RequireDebugFalse",
  190. }
  191. logging_config["handlers"]["mail_admins"]["filters"] = [filter_name]