PageRenderTime 61ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/simplegallery/build/Django/django/conf/__init__.py

https://bitbucket.org/pythonegrove/semih
Python | 170 lines | 110 code | 20 blank | 40 comment | 19 complexity | 2e0759b08fe7334166044bd2226f38fb 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
  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. elif name == "ALLOWED_INCLUDE_ROOTS" and isinstance(value, basestring):
  63. raise ValueError("The ALLOWED_INCLUDE_ROOTS setting must be set "
  64. "to a tuple, not a string.")
  65. object.__setattr__(self, name, value)
  66. class Settings(BaseSettings):
  67. def __init__(self, settings_module):
  68. # update this dict from global settings (but only for ALL_CAPS settings)
  69. for setting in dir(global_settings):
  70. if setting == setting.upper():
  71. setattr(self, setting, getattr(global_settings, setting))
  72. # store the settings module in case someone later cares
  73. self.SETTINGS_MODULE = settings_module
  74. try:
  75. mod = importlib.import_module(self.SETTINGS_MODULE)
  76. except ImportError, e:
  77. raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
  78. # Settings that should be converted into tuples if they're mistakenly entered
  79. # as strings.
  80. tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS")
  81. for setting in dir(mod):
  82. if setting == setting.upper():
  83. setting_value = getattr(mod, setting)
  84. if setting in tuple_settings and type(setting_value) == str:
  85. setting_value = (setting_value,) # In case the user forgot the comma.
  86. setattr(self, setting, setting_value)
  87. # Expand entries in INSTALLED_APPS like "django.contrib.*" to a list
  88. # of all those apps.
  89. new_installed_apps = []
  90. for app in self.INSTALLED_APPS:
  91. if app.endswith('.*'):
  92. app_mod = importlib.import_module(app[:-2])
  93. appdir = os.path.dirname(app_mod.__file__)
  94. app_subdirs = os.listdir(appdir)
  95. app_subdirs.sort()
  96. name_pattern = re.compile(r'[a-zA-Z]\w*')
  97. for d in app_subdirs:
  98. if name_pattern.match(d) and os.path.isdir(os.path.join(appdir, d)):
  99. new_installed_apps.append('%s.%s' % (app[:-2], d))
  100. else:
  101. new_installed_apps.append(app)
  102. self.INSTALLED_APPS = new_installed_apps
  103. if hasattr(time, 'tzset') and self.TIME_ZONE:
  104. # When we can, attempt to validate the timezone. If we can't find
  105. # this file, no check happens and it's harmless.
  106. zoneinfo_root = '/usr/share/zoneinfo'
  107. if (os.path.exists(zoneinfo_root) and not
  108. os.path.exists(os.path.join(zoneinfo_root, *(self.TIME_ZONE.split('/'))))):
  109. raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
  110. # Move the time zone info into os.environ. See ticket #2315 for why
  111. # we don't do this unconditionally (breaks Windows).
  112. os.environ['TZ'] = self.TIME_ZONE
  113. time.tzset()
  114. # Settings are configured, so we can set up the logger if required
  115. if self.LOGGING_CONFIG:
  116. # First find the logging configuration function ...
  117. logging_config_path, logging_config_func_name = self.LOGGING_CONFIG.rsplit('.', 1)
  118. logging_config_module = importlib.import_module(logging_config_path)
  119. logging_config_func = getattr(logging_config_module, logging_config_func_name)
  120. # ... then invoke it with the logging settings
  121. logging_config_func(self.LOGGING)
  122. class UserSettingsHolder(BaseSettings):
  123. """
  124. Holder for user configured settings.
  125. """
  126. # SETTINGS_MODULE doesn't make much sense in the manually configured
  127. # (standalone) case.
  128. SETTINGS_MODULE = None
  129. def __init__(self, default_settings):
  130. """
  131. Requests for configuration variables not in this class are satisfied
  132. from the module specified in default_settings (if possible).
  133. """
  134. self.default_settings = default_settings
  135. def __getattr__(self, name):
  136. return getattr(self.default_settings, name)
  137. def __dir__(self):
  138. return self.__dict__.keys() + dir(self.default_settings)
  139. # For Python < 2.6:
  140. __members__ = property(lambda self: self.__dir__())
  141. settings = LazySettings()