PageRenderTime 67ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/django/conf/__init__.py

https://github.com/jobicoppola/django
Python | 208 lines | 136 code | 28 blank | 44 comment | 20 complexity | f84b5f57a6944b4586a61b6dd6fb5584 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 os
  8. import re
  9. import time # Needed for Windows
  10. import warnings
  11. from django.conf import global_settings
  12. from django.utils.functional import LazyObject, empty
  13. from django.utils import importlib
  14. ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE"
  15. class LazySettings(LazyObject):
  16. """
  17. A lazy proxy for either global Django settings or a custom settings object.
  18. The user can manually configure settings prior to using them. Otherwise,
  19. Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE.
  20. """
  21. def _setup(self):
  22. """
  23. Load the settings module pointed to by the environment variable. This
  24. is used the first time we need any settings at all, if the user has not
  25. previously configured the settings manually.
  26. """
  27. try:
  28. settings_module = os.environ[ENVIRONMENT_VARIABLE]
  29. if not settings_module: # If it's set but is an empty string.
  30. raise KeyError
  31. except KeyError:
  32. # NOTE: This is arguably an EnvironmentError, but that causes
  33. # problems with Python's interactive help.
  34. raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
  35. self._wrapped = Settings(settings_module)
  36. def configure(self, default_settings=global_settings, **options):
  37. """
  38. Called to manually configure the settings. The 'default_settings'
  39. parameter sets where to retrieve any unspecified values from (its
  40. argument must support attribute access (__getattr__)).
  41. """
  42. if self._wrapped is not empty:
  43. raise RuntimeError('Settings already configured.')
  44. holder = UserSettingsHolder(default_settings)
  45. for name, value in options.items():
  46. setattr(holder, name, value)
  47. self._wrapped = holder
  48. @property
  49. def configured(self):
  50. """
  51. Returns True if the settings have already been configured.
  52. """
  53. return self._wrapped is not empty
  54. class BaseSettings(object):
  55. """
  56. Common logic for settings whether set by a module or by the user.
  57. """
  58. def __setattr__(self, name, value):
  59. if name in ("MEDIA_URL", "STATIC_URL") and value and not value.endswith('/'):
  60. warnings.warn('If set, %s must end with a slash' % name,
  61. DeprecationWarning)
  62. object.__setattr__(self, name, value)
  63. class Settings(BaseSettings):
  64. def __init__(self, settings_module):
  65. # update this dict from global settings (but only for ALL_CAPS settings)
  66. for setting in dir(global_settings):
  67. if setting == setting.upper():
  68. setattr(self, setting, getattr(global_settings, setting))
  69. # store the settings module in case someone later cares
  70. self.SETTINGS_MODULE = settings_module
  71. try:
  72. mod = importlib.import_module(self.SETTINGS_MODULE)
  73. except ImportError, e:
  74. raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
  75. # Settings that should be converted into tuples if they're mistakenly entered
  76. # as strings.
  77. tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS")
  78. for setting in dir(mod):
  79. if setting == setting.upper():
  80. setting_value = getattr(mod, setting)
  81. if setting in tuple_settings and type(setting_value) == str:
  82. setting_value = (setting_value,) # In case the user forgot the comma.
  83. setattr(self, setting, setting_value)
  84. # Expand entries in INSTALLED_APPS like "django.contrib.*" to a list
  85. # of all those apps.
  86. new_installed_apps = []
  87. for app in self.INSTALLED_APPS:
  88. if app.endswith('.*'):
  89. app_mod = importlib.import_module(app[:-2])
  90. appdir = os.path.dirname(app_mod.__file__)
  91. app_subdirs = os.listdir(appdir)
  92. app_subdirs.sort()
  93. name_pattern = re.compile(r'[a-zA-Z]\w*')
  94. for d in app_subdirs:
  95. if name_pattern.match(d) and os.path.isdir(os.path.join(appdir, d)):
  96. new_installed_apps.append('%s.%s' % (app[:-2], d))
  97. else:
  98. new_installed_apps.append(app)
  99. self.INSTALLED_APPS = new_installed_apps
  100. if hasattr(time, 'tzset') and self.TIME_ZONE:
  101. # When we can, attempt to validate the timezone. If we can't find
  102. # this file, no check happens and it's harmless.
  103. zoneinfo_root = '/usr/share/zoneinfo'
  104. if (os.path.exists(zoneinfo_root) and not
  105. os.path.exists(os.path.join(zoneinfo_root, *(self.TIME_ZONE.split('/'))))):
  106. raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
  107. # Move the time zone info into os.environ. See ticket #2315 for why
  108. # we don't do this unconditionally (breaks Windows).
  109. os.environ['TZ'] = self.TIME_ZONE
  110. time.tzset()
  111. # Settings are configured, so we can set up the logger if required
  112. if self.LOGGING_CONFIG:
  113. # First find the logging configuration function ...
  114. logging_config_path, logging_config_func_name = self.LOGGING_CONFIG.rsplit('.', 1)
  115. logging_config_module = importlib.import_module(logging_config_path)
  116. logging_config_func = getattr(logging_config_module, logging_config_func_name)
  117. # Backwards-compatibility shim for #16288 fix
  118. compat_patch_logging_config(self.LOGGING)
  119. # ... then invoke it with the logging settings
  120. logging_config_func(self.LOGGING)
  121. class UserSettingsHolder(BaseSettings):
  122. """
  123. Holder for user configured settings.
  124. """
  125. # SETTINGS_MODULE doesn't make much sense in the manually configured
  126. # (standalone) case.
  127. SETTINGS_MODULE = None
  128. def __init__(self, default_settings):
  129. """
  130. Requests for configuration variables not in this class are satisfied
  131. from the module specified in default_settings (if possible).
  132. """
  133. self.default_settings = default_settings
  134. def __getattr__(self, name):
  135. return getattr(self.default_settings, name)
  136. def __dir__(self):
  137. return self.__dict__.keys() + dir(self.default_settings)
  138. # For Python < 2.6:
  139. __members__ = property(lambda self: self.__dir__())
  140. settings = LazySettings()
  141. def compat_patch_logging_config(logging_config):
  142. """
  143. Backwards-compatibility shim for #16288 fix. Takes initial value of
  144. ``LOGGING`` setting and patches it in-place (issuing deprecation warning)
  145. if "mail_admins" logging handler is configured but has no filters.
  146. """
  147. # Shim only if LOGGING["handlers"]["mail_admins"] exists,
  148. # but has no "filters" key
  149. if "filters" not in logging_config.get(
  150. "handlers", {}).get(
  151. "mail_admins", {"filters": []}):
  152. warnings.warn(
  153. "You have no filters defined on the 'mail_admins' logging "
  154. "handler: adding implicit debug-false-only filter. "
  155. "See http://docs.djangoproject.com/en/dev/releases/1.4/"
  156. "#request-exceptions-are-now-always-logged",
  157. PendingDeprecationWarning)
  158. filter_name = "require_debug_false"
  159. filters = logging_config.setdefault("filters", {})
  160. while filter_name in filters:
  161. filter_name = filter_name + "_"
  162. def _callback(record):
  163. from django.conf import settings
  164. return not settings.DEBUG
  165. filters[filter_name] = {
  166. "()": "django.utils.log.CallbackFilter",
  167. "callback": _callback
  168. }
  169. logging_config["handlers"]["mail_admins"]["filters"] = [filter_name]