PageRenderTime 40ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/django/conf/__init__.py

https://github.com/rohanza/django
Python | 167 lines | 107 code | 20 blank | 40 comment | 19 complexity | a24a462f39389ea56784cfe122197d0e 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
  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. 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. PendingDeprecationWarning)
  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? Does it have syntax errors?): %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. # ... then invoke it with the logging settings
  118. logging_config_func(self.LOGGING)
  119. class UserSettingsHolder(BaseSettings):
  120. """
  121. Holder for user configured settings.
  122. """
  123. # SETTINGS_MODULE doesn't make much sense in the manually configured
  124. # (standalone) case.
  125. SETTINGS_MODULE = None
  126. def __init__(self, default_settings):
  127. """
  128. Requests for configuration variables not in this class are satisfied
  129. from the module specified in default_settings (if possible).
  130. """
  131. self.default_settings = default_settings
  132. def __getattr__(self, name):
  133. return getattr(self.default_settings, name)
  134. def __dir__(self):
  135. return self.__dict__.keys() + dir(self.default_settings)
  136. # For Python < 2.6:
  137. __members__ = property(lambda self: self.__dir__())
  138. settings = LazySettings()