PageRenderTime 67ms CodeModel.GetById 37ms RepoModel.GetById 3ms app.codeStats 0ms

/venv/Lib/site-packages/django/conf/__init__.py

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