PageRenderTime 48ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/django/conf/__init__.py

https://code.google.com/p/mango-py/
Python | 229 lines | 157 code | 28 blank | 44 comment | 20 complexity | 7069b3905488515a832b84ba3e42ab08 MD5 | raw file
Possible License(s): BSD-3-Clause
  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, sys
  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
  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 != None:
  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. def configured(self):
  49. """
  50. Returns True if the settings have already been configured.
  51. """
  52. return bool(self._wrapped)
  53. configured = property(configured)
  54. def import_settings_module_with_extras(settings_module):
  55. parts = settings_module.split(".")
  56. parts[-1]+=".py"
  57. found = []
  58. for path in ["."]+sys.path:
  59. search = os.path.join(path,*parts)
  60. if os.path.exists(search) and os.path.isfile(search):
  61. found.append(search)
  62. if 'PROJECT_DIRECTORY' not in os.environ:
  63. os.environ['PROJECT_DIRECTORY']=os.path.dirname(os.path.abspath(found[0]))
  64. if 'SCRIPT_NAME' not in os.environ: # this will be missing if we are running on the internal server
  65. os.environ['SCRIPT_NAME']=''
  66. try:
  67. mod = importlib.import_module(settings_module)
  68. except ImportError, e:
  69. raise ImportError("Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (ENVIRONMENT_VARIABLE, e))
  70. return mod
  71. class BaseSettings(object):
  72. """
  73. Common logic for settings whether set by a module or by the user.
  74. """
  75. def __setattr__(self, name, value):
  76. if name in ("MEDIA_URL", "STATIC_URL") and value and not value.endswith('/'):
  77. warnings.warn('If set, %s must end with a slash' % name,
  78. PendingDeprecationWarning)
  79. object.__setattr__(self, name, value)
  80. class Settings(BaseSettings):
  81. def __init__(self, settings_module):
  82. # update this dict from global settings (but only for ALL_CAPS settings)
  83. for setting in dir(global_settings):
  84. if setting == setting.upper():
  85. setattr(self, setting, getattr(global_settings, setting))
  86. # store the settings module in case someone later cares
  87. self.SETTINGS_MODULE = settings_module
  88. try:
  89. mod = importlib.import_module(self.SETTINGS_MODULE)
  90. except ImportError, e:
  91. raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
  92. # Settings that should be converted into tuples if they're mistakenly entered
  93. # as strings.
  94. tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS")
  95. for setting in dir(mod):
  96. if setting == setting.upper():
  97. setting_value = getattr(mod, setting)
  98. if setting in tuple_settings and type(setting_value) == str:
  99. setting_value = (setting_value,) # In case the user forgot the comma.
  100. setattr(self, setting, setting_value)
  101. # Expand entries in INSTALLED_APPS like "django.contrib.*" to a list
  102. # of all those apps.
  103. new_installed_apps = []
  104. for app in self.INSTALLED_APPS:
  105. if app.endswith('.*'):
  106. app_mod = importlib.import_module(app[:-2])
  107. appdir = os.path.dirname(app_mod.__file__)
  108. app_subdirs = os.listdir(appdir)
  109. app_subdirs.sort()
  110. name_pattern = re.compile(r'[a-zA-Z]\w*')
  111. for d in app_subdirs:
  112. if name_pattern.match(d) and os.path.isdir(os.path.join(appdir, d)):
  113. new_installed_apps.append('%s.%s' % (app[:-2], d))
  114. else:
  115. new_installed_apps.append(app)
  116. self.INSTALLED_APPS = new_installed_apps
  117. if hasattr(time, 'tzset') and self.TIME_ZONE:
  118. # When we can, attempt to validate the timezone. If we can't find
  119. # this file, no check happens and it's harmless.
  120. zoneinfo_root = '/usr/share/zoneinfo'
  121. if (os.path.exists(zoneinfo_root) and not
  122. os.path.exists(os.path.join(zoneinfo_root, *(self.TIME_ZONE.split('/'))))):
  123. raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
  124. # Move the time zone info into os.environ. See ticket #2315 for why
  125. # we don't do this unconditionally (breaks Windows).
  126. os.environ['TZ'] = self.TIME_ZONE
  127. time.tzset()
  128. # Settings are configured, so we can set up the logger if required
  129. if self.LOGGING_CONFIG:
  130. # First find the logging configuration function ...
  131. logging_config_path, logging_config_func_name = self.LOGGING_CONFIG.rsplit('.', 1)
  132. logging_config_module = importlib.import_module(logging_config_path)
  133. logging_config_func = getattr(logging_config_module, logging_config_func_name)
  134. # Backwards-compatibility shim for #16288 fix
  135. compat_patch_logging_config(self.LOGGING)
  136. # ... then invoke it with the logging settings
  137. logging_config_func(self.LOGGING)
  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.default_settings = default_settings
  151. def __getattr__(self, name):
  152. return getattr(self.default_settings, name)
  153. def __dir__(self):
  154. return self.__dict__.keys() + dir(self.default_settings)
  155. # For Python < 2.6:
  156. __members__ = property(lambda self: self.__dir__())
  157. settings = LazySettings()
  158. def compat_patch_logging_config(logging_config):
  159. """
  160. Backwards-compatibility shim for #16288 fix. Takes initial value of
  161. ``LOGGING`` setting and patches it in-place (issuing deprecation warning)
  162. if "mail_admins" logging handler is configured but has no filters.
  163. """
  164. # Shim only if LOGGING["handlers"]["mail_admins"] exists,
  165. # but has no "filters" key
  166. if "filters" not in logging_config.get(
  167. "handlers", {}).get(
  168. "mail_admins", {"filters": []}):
  169. warnings.warn(
  170. "You have no filters defined on the 'mail_admins' logging "
  171. "handler: adding implicit debug-false-only filter. "
  172. "See http://docs.djangoproject.com/en/dev/releases/1.4/"
  173. "#request-exceptions-are-now-always-logged",
  174. PendingDeprecationWarning)
  175. filter_name = "require_debug_false"
  176. filters = logging_config.setdefault("filters", {})
  177. while filter_name in filters:
  178. filter_name = filter_name + "_"
  179. def _callback(record):
  180. from django.conf import settings
  181. return not settings.DEBUG
  182. filters[filter_name] = {
  183. "()": "django.utils.log.CallbackFilter",
  184. "callback": _callback
  185. }
  186. logging_config["handlers"]["mail_admins"]["filters"] = [filter_name]