__init__.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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 importlib
  8. import os
  9. import time # Needed for Windows
  10. from django.conf import global_settings
  11. from django.core.exceptions import ImproperlyConfigured
  12. from django.utils.functional import LazyObject, empty
  13. from django.utils import six
  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, name=None):
  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. settings_module = os.environ.get(ENVIRONMENT_VARIABLE)
  28. if not settings_module:
  29. desc = ("setting %s" % name) if name else "settings"
  30. raise ImproperlyConfigured(
  31. "Requested %s, but settings are not configured. "
  32. "You must either define the environment variable %s "
  33. "or call settings.configure() before accessing settings."
  34. % (desc, ENVIRONMENT_VARIABLE))
  35. self._wrapped = Settings(settings_module)
  36. def __getattr__(self, name):
  37. if self._wrapped is empty:
  38. self._setup(name)
  39. return getattr(self._wrapped, name)
  40. def configure(self, default_settings=global_settings, **options):
  41. """
  42. Called to manually configure the settings. The 'default_settings'
  43. parameter sets where to retrieve any unspecified values from (its
  44. argument must support attribute access (__getattr__)).
  45. """
  46. if self._wrapped is not empty:
  47. raise RuntimeError('Settings already configured.')
  48. holder = UserSettingsHolder(default_settings)
  49. for name, value in options.items():
  50. setattr(holder, name, value)
  51. self._wrapped = holder
  52. @property
  53. def configured(self):
  54. """
  55. Returns True if the settings have already been configured.
  56. """
  57. return self._wrapped is not empty
  58. class BaseSettings(object):
  59. """
  60. Common logic for settings whether set by a module or by the user.
  61. """
  62. def __setattr__(self, name, value):
  63. if name in ("MEDIA_URL", "STATIC_URL") and value and not value.endswith('/'):
  64. raise ImproperlyConfigured("If set, %s must end with a slash" % name)
  65. elif name == "ALLOWED_INCLUDE_ROOTS" and isinstance(value, six.string_types):
  66. raise ValueError("The ALLOWED_INCLUDE_ROOTS setting must be set "
  67. "to a tuple, not a string.")
  68. object.__setattr__(self, name, value)
  69. class Settings(BaseSettings):
  70. def __init__(self, settings_module):
  71. # update this dict from global settings (but only for ALL_CAPS settings)
  72. for setting in dir(global_settings):
  73. if setting.isupper():
  74. setattr(self, setting, getattr(global_settings, setting))
  75. # store the settings module in case someone later cares
  76. self.SETTINGS_MODULE = settings_module
  77. try:
  78. mod = importlib.import_module(self.SETTINGS_MODULE)
  79. except ImportError as e:
  80. raise ImportError(
  81. "Could not import settings '%s' (Is it on sys.path? Is there an import error in the settings file?): %s"
  82. % (self.SETTINGS_MODULE, e)
  83. )
  84. tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS")
  85. self._explicit_settings = set()
  86. for setting in dir(mod):
  87. if setting.isupper():
  88. setting_value = getattr(mod, setting)
  89. if (setting in tuple_settings and
  90. isinstance(setting_value, six.string_types)):
  91. raise ImproperlyConfigured("The %s setting must be a tuple. "
  92. "Please fix your settings." % setting)
  93. setattr(self, setting, setting_value)
  94. self._explicit_settings.add(setting)
  95. if not self.SECRET_KEY:
  96. raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
  97. if hasattr(time, 'tzset') and self.TIME_ZONE:
  98. # When we can, attempt to validate the timezone. If we can't find
  99. # this file, no check happens and it's harmless.
  100. zoneinfo_root = '/usr/share/zoneinfo'
  101. if (os.path.exists(zoneinfo_root) and not
  102. os.path.exists(os.path.join(zoneinfo_root, *(self.TIME_ZONE.split('/'))))):
  103. raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
  104. # Move the time zone info into os.environ. See ticket #2315 for why
  105. # we don't do this unconditionally (breaks Windows).
  106. os.environ['TZ'] = self.TIME_ZONE
  107. time.tzset()
  108. def is_overridden(self, setting):
  109. return setting in self._explicit_settings
  110. class UserSettingsHolder(BaseSettings):
  111. """
  112. Holder for user configured settings.
  113. """
  114. # SETTINGS_MODULE doesn't make much sense in the manually configured
  115. # (standalone) case.
  116. SETTINGS_MODULE = None
  117. def __init__(self, default_settings):
  118. """
  119. Requests for configuration variables not in this class are satisfied
  120. from the module specified in default_settings (if possible).
  121. """
  122. self.__dict__['_deleted'] = set()
  123. self.default_settings = default_settings
  124. def __getattr__(self, name):
  125. if name in self._deleted:
  126. raise AttributeError
  127. return getattr(self.default_settings, name)
  128. def __setattr__(self, name, value):
  129. self._deleted.discard(name)
  130. super(UserSettingsHolder, self).__setattr__(name, value)
  131. def __delattr__(self, name):
  132. self._deleted.add(name)
  133. if hasattr(self, name):
  134. super(UserSettingsHolder, self).__delattr__(name)
  135. def __dir__(self):
  136. return list(self.__dict__) + dir(self.default_settings)
  137. def is_overridden(self, setting):
  138. deleted = (setting in self._deleted)
  139. set_locally = (setting in self.__dict__)
  140. set_on_default = getattr(self.default_settings, 'is_overridden', lambda s: False)(setting)
  141. return (deleted or set_locally or set_on_default)
  142. settings = LazySettings()