You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

__init__.py 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. """
  2. Settings and configuration for Django.
  3. Read values from the module specified by the DJANGO_SETTINGS_MODULE environment
  4. variable, and then from django.conf.global_settings; see the global_settings.py
  5. for a list of all possible variables.
  6. """
  7. import importlib
  8. import os
  9. import time
  10. import traceback
  11. import warnings
  12. from pathlib import Path
  13. import django
  14. from django.conf import global_settings
  15. from django.core.exceptions import ImproperlyConfigured
  16. from django.utils.deprecation import (
  17. RemovedInDjango30Warning, RemovedInDjango31Warning,
  18. )
  19. from django.utils.functional import LazyObject, empty
  20. ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE"
  21. DEFAULT_CONTENT_TYPE_DEPRECATED_MSG = 'The DEFAULT_CONTENT_TYPE setting is deprecated.'
  22. FILE_CHARSET_DEPRECATED_MSG = (
  23. 'The FILE_CHARSET setting is deprecated. Starting with Django 3.1, all '
  24. 'files read from disk must be UTF-8 encoded.'
  25. )
  26. class SettingsReference(str):
  27. """
  28. String subclass which references a current settings value. It's treated as
  29. the value in memory but serializes to a settings.NAME attribute reference.
  30. """
  31. def __new__(self, value, setting_name):
  32. return str.__new__(self, value)
  33. def __init__(self, value, setting_name):
  34. self.setting_name = setting_name
  35. class LazySettings(LazyObject):
  36. """
  37. A lazy proxy for either global Django settings or a custom settings object.
  38. The user can manually configure settings prior to using them. Otherwise,
  39. Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE.
  40. """
  41. def _setup(self, name=None):
  42. """
  43. Load the settings module pointed to by the environment variable. This
  44. is used the first time settings are needed, if the user hasn't
  45. configured settings manually.
  46. """
  47. settings_module = os.environ.get(ENVIRONMENT_VARIABLE)
  48. if not settings_module:
  49. desc = ("setting %s" % name) if name else "settings"
  50. raise ImproperlyConfigured(
  51. "Requested %s, but settings are not configured. "
  52. "You must either define the environment variable %s "
  53. "or call settings.configure() before accessing settings."
  54. % (desc, ENVIRONMENT_VARIABLE))
  55. self._wrapped = Settings(settings_module)
  56. def __repr__(self):
  57. # Hardcode the class name as otherwise it yields 'Settings'.
  58. if self._wrapped is empty:
  59. return '<LazySettings [Unevaluated]>'
  60. return '<LazySettings "%(settings_module)s">' % {
  61. 'settings_module': self._wrapped.SETTINGS_MODULE,
  62. }
  63. def __getattr__(self, name):
  64. """Return the value of a setting and cache it in self.__dict__."""
  65. if self._wrapped is empty:
  66. self._setup(name)
  67. val = getattr(self._wrapped, name)
  68. self.__dict__[name] = val
  69. return val
  70. def __setattr__(self, name, value):
  71. """
  72. Set the value of setting. Clear all cached values if _wrapped changes
  73. (@override_settings does this) or clear single values when set.
  74. """
  75. if name == '_wrapped':
  76. self.__dict__.clear()
  77. else:
  78. self.__dict__.pop(name, None)
  79. super().__setattr__(name, value)
  80. def __delattr__(self, name):
  81. """Delete a setting and clear it from cache if needed."""
  82. super().__delattr__(name)
  83. self.__dict__.pop(name, None)
  84. def configure(self, default_settings=global_settings, **options):
  85. """
  86. Called to manually configure the settings. The 'default_settings'
  87. parameter sets where to retrieve any unspecified values from (its
  88. argument must support attribute access (__getattr__)).
  89. """
  90. if self._wrapped is not empty:
  91. raise RuntimeError('Settings already configured.')
  92. holder = UserSettingsHolder(default_settings)
  93. for name, value in options.items():
  94. setattr(holder, name, value)
  95. self._wrapped = holder
  96. @property
  97. def configured(self):
  98. """Return True if the settings have already been configured."""
  99. return self._wrapped is not empty
  100. @property
  101. def DEFAULT_CONTENT_TYPE(self):
  102. stack = traceback.extract_stack()
  103. # Show a warning if the setting is used outside of Django.
  104. # Stack index: -1 this line, -2 the caller.
  105. filename, _line_number, _function_name, _text = stack[-2]
  106. if not filename.startswith(os.path.dirname(django.__file__)):
  107. warnings.warn(
  108. DEFAULT_CONTENT_TYPE_DEPRECATED_MSG,
  109. RemovedInDjango30Warning,
  110. stacklevel=2,
  111. )
  112. return self.__getattr__('DEFAULT_CONTENT_TYPE')
  113. @property
  114. def FILE_CHARSET(self):
  115. stack = traceback.extract_stack()
  116. # Show a warning if the setting is used outside of Django.
  117. # Stack index: -1 this line, -2 the caller.
  118. filename, _line_number, _function_name, _text = stack[-2]
  119. if not filename.startswith(os.path.dirname(django.__file__)):
  120. warnings.warn(
  121. FILE_CHARSET_DEPRECATED_MSG,
  122. RemovedInDjango31Warning,
  123. stacklevel=2,
  124. )
  125. return self.__getattr__('FILE_CHARSET')
  126. class Settings:
  127. def __init__(self, settings_module):
  128. # update this dict from global settings (but only for ALL_CAPS settings)
  129. for setting in dir(global_settings):
  130. if setting.isupper():
  131. setattr(self, setting, getattr(global_settings, setting))
  132. # store the settings module in case someone later cares
  133. self.SETTINGS_MODULE = settings_module
  134. mod = importlib.import_module(self.SETTINGS_MODULE)
  135. tuple_settings = (
  136. "INSTALLED_APPS",
  137. "TEMPLATE_DIRS",
  138. "LOCALE_PATHS",
  139. )
  140. self._explicit_settings = set()
  141. for setting in dir(mod):
  142. if setting.isupper():
  143. setting_value = getattr(mod, setting)
  144. if (setting in tuple_settings and
  145. not isinstance(setting_value, (list, tuple))):
  146. raise ImproperlyConfigured("The %s setting must be a list or a tuple. " % setting)
  147. setattr(self, setting, setting_value)
  148. self._explicit_settings.add(setting)
  149. if not self.SECRET_KEY:
  150. raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
  151. if self.is_overridden('DEFAULT_CONTENT_TYPE'):
  152. warnings.warn(DEFAULT_CONTENT_TYPE_DEPRECATED_MSG, RemovedInDjango30Warning)
  153. if self.is_overridden('FILE_CHARSET'):
  154. warnings.warn(FILE_CHARSET_DEPRECATED_MSG, RemovedInDjango31Warning)
  155. if hasattr(time, 'tzset') and self.TIME_ZONE:
  156. # When we can, attempt to validate the timezone. If we can't find
  157. # this file, no check happens and it's harmless.
  158. zoneinfo_root = Path('/usr/share/zoneinfo')
  159. zone_info_file = zoneinfo_root.joinpath(*self.TIME_ZONE.split('/'))
  160. if zoneinfo_root.exists() and not zone_info_file.exists():
  161. raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
  162. # Move the time zone info into os.environ. See ticket #2315 for why
  163. # we don't do this unconditionally (breaks Windows).
  164. os.environ['TZ'] = self.TIME_ZONE
  165. time.tzset()
  166. def is_overridden(self, setting):
  167. return setting in self._explicit_settings
  168. def __repr__(self):
  169. return '<%(cls)s "%(settings_module)s">' % {
  170. 'cls': self.__class__.__name__,
  171. 'settings_module': self.SETTINGS_MODULE,
  172. }
  173. class UserSettingsHolder:
  174. """Holder for user configured settings."""
  175. # SETTINGS_MODULE doesn't make much sense in the manually configured
  176. # (standalone) case.
  177. SETTINGS_MODULE = None
  178. def __init__(self, default_settings):
  179. """
  180. Requests for configuration variables not in this class are satisfied
  181. from the module specified in default_settings (if possible).
  182. """
  183. self.__dict__['_deleted'] = set()
  184. self.default_settings = default_settings
  185. def __getattr__(self, name):
  186. if name in self._deleted:
  187. raise AttributeError
  188. return getattr(self.default_settings, name)
  189. def __setattr__(self, name, value):
  190. self._deleted.discard(name)
  191. if name == 'DEFAULT_CONTENT_TYPE':
  192. warnings.warn(DEFAULT_CONTENT_TYPE_DEPRECATED_MSG, RemovedInDjango30Warning)
  193. elif name == 'FILE_CHARSET':
  194. warnings.warn(FILE_CHARSET_DEPRECATED_MSG, RemovedInDjango31Warning)
  195. super().__setattr__(name, value)
  196. def __delattr__(self, name):
  197. self._deleted.add(name)
  198. if hasattr(self, name):
  199. super().__delattr__(name)
  200. def __dir__(self):
  201. return sorted(
  202. s for s in [*self.__dict__, *dir(self.default_settings)]
  203. if s not in self._deleted
  204. )
  205. def is_overridden(self, setting):
  206. deleted = (setting in self._deleted)
  207. set_locally = (setting in self.__dict__)
  208. set_on_default = getattr(self.default_settings, 'is_overridden', lambda s: False)(setting)
  209. return deleted or set_locally or set_on_default
  210. def __repr__(self):
  211. return '<%(cls)s>' % {
  212. 'cls': self.__class__.__name__,
  213. }
  214. settings = LazySettings()