__init__.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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 RemovedInDjango50Warning, RemovedInDjango51Warning
  17. from django.utils.functional import LazyObject, empty
  18. ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE"
  19. DEFAULT_STORAGE_ALIAS = "default"
  20. STATICFILES_STORAGE_ALIAS = "staticfiles"
  21. # RemovedInDjango50Warning
  22. USE_DEPRECATED_PYTZ_DEPRECATED_MSG = (
  23. "The USE_DEPRECATED_PYTZ setting, and support for pytz timezones is "
  24. "deprecated in favor of the stdlib zoneinfo module. Please update your "
  25. "code to use zoneinfo and remove the USE_DEPRECATED_PYTZ setting."
  26. )
  27. USE_L10N_DEPRECATED_MSG = (
  28. "The USE_L10N setting is deprecated. Starting with Django 5.0, localized "
  29. "formatting of data will always be enabled. For example Django will "
  30. "display numbers and dates using the format of the current locale."
  31. )
  32. CSRF_COOKIE_MASKED_DEPRECATED_MSG = (
  33. "The CSRF_COOKIE_MASKED transitional setting is deprecated. Support for "
  34. "it will be removed in Django 5.0."
  35. )
  36. DEFAULT_FILE_STORAGE_DEPRECATED_MSG = (
  37. "The DEFAULT_FILE_STORAGE setting is deprecated. Use STORAGES instead."
  38. )
  39. STATICFILES_STORAGE_DEPRECATED_MSG = (
  40. "The STATICFILES_STORAGE setting is deprecated. Use STORAGES instead."
  41. )
  42. class SettingsReference(str):
  43. """
  44. String subclass which references a current settings value. It's treated as
  45. the value in memory but serializes to a settings.NAME attribute reference.
  46. """
  47. def __new__(self, value, setting_name):
  48. return str.__new__(self, value)
  49. def __init__(self, value, setting_name):
  50. self.setting_name = setting_name
  51. class LazySettings(LazyObject):
  52. """
  53. A lazy proxy for either global Django settings or a custom settings object.
  54. The user can manually configure settings prior to using them. Otherwise,
  55. Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE.
  56. """
  57. def _setup(self, name=None):
  58. """
  59. Load the settings module pointed to by the environment variable. This
  60. is used the first time settings are needed, if the user hasn't
  61. configured settings manually.
  62. """
  63. settings_module = os.environ.get(ENVIRONMENT_VARIABLE)
  64. if not settings_module:
  65. desc = ("setting %s" % name) if name else "settings"
  66. raise ImproperlyConfigured(
  67. "Requested %s, but settings are not configured. "
  68. "You must either define the environment variable %s "
  69. "or call settings.configure() before accessing settings."
  70. % (desc, ENVIRONMENT_VARIABLE)
  71. )
  72. self._wrapped = Settings(settings_module)
  73. def __repr__(self):
  74. # Hardcode the class name as otherwise it yields 'Settings'.
  75. if self._wrapped is empty:
  76. return "<LazySettings [Unevaluated]>"
  77. return '<LazySettings "%(settings_module)s">' % {
  78. "settings_module": self._wrapped.SETTINGS_MODULE,
  79. }
  80. def __getattr__(self, name):
  81. """Return the value of a setting and cache it in self.__dict__."""
  82. if (_wrapped := self._wrapped) is empty:
  83. self._setup(name)
  84. _wrapped = self._wrapped
  85. val = getattr(_wrapped, name)
  86. # Special case some settings which require further modification.
  87. # This is done here for performance reasons so the modified value is cached.
  88. if name in {"MEDIA_URL", "STATIC_URL"} and val is not None:
  89. val = self._add_script_prefix(val)
  90. elif name == "SECRET_KEY" and not val:
  91. raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
  92. self.__dict__[name] = val
  93. return val
  94. def __setattr__(self, name, value):
  95. """
  96. Set the value of setting. Clear all cached values if _wrapped changes
  97. (@override_settings does this) or clear single values when set.
  98. """
  99. if name == "_wrapped":
  100. self.__dict__.clear()
  101. else:
  102. self.__dict__.pop(name, None)
  103. super().__setattr__(name, value)
  104. def __delattr__(self, name):
  105. """Delete a setting and clear it from cache if needed."""
  106. super().__delattr__(name)
  107. self.__dict__.pop(name, None)
  108. def configure(self, default_settings=global_settings, **options):
  109. """
  110. Called to manually configure the settings. The 'default_settings'
  111. parameter sets where to retrieve any unspecified values from (its
  112. argument must support attribute access (__getattr__)).
  113. """
  114. if self._wrapped is not empty:
  115. raise RuntimeError("Settings already configured.")
  116. holder = UserSettingsHolder(default_settings)
  117. for name, value in options.items():
  118. if not name.isupper():
  119. raise TypeError("Setting %r must be uppercase." % name)
  120. setattr(holder, name, value)
  121. self._wrapped = holder
  122. @staticmethod
  123. def _add_script_prefix(value):
  124. """
  125. Add SCRIPT_NAME prefix to relative paths.
  126. Useful when the app is being served at a subpath and manually prefixing
  127. subpath to STATIC_URL and MEDIA_URL in settings is inconvenient.
  128. """
  129. # Don't apply prefix to absolute paths and URLs.
  130. if value.startswith(("http://", "https://", "/")):
  131. return value
  132. from django.urls import get_script_prefix
  133. return "%s%s" % (get_script_prefix(), value)
  134. @property
  135. def configured(self):
  136. """Return True if the settings have already been configured."""
  137. return self._wrapped is not empty
  138. def _show_deprecation_warning(self, message, category):
  139. stack = traceback.extract_stack()
  140. # Show a warning if the setting is used outside of Django.
  141. # Stack index: -1 this line, -2 the property, -3 the
  142. # LazyObject __getattribute__(), -4 the caller.
  143. filename, _, _, _ = stack[-4]
  144. if not filename.startswith(os.path.dirname(django.__file__)):
  145. warnings.warn(message, category, stacklevel=2)
  146. @property
  147. def USE_L10N(self):
  148. self._show_deprecation_warning(
  149. USE_L10N_DEPRECATED_MSG, RemovedInDjango50Warning
  150. )
  151. return self.__getattr__("USE_L10N")
  152. # RemovedInDjango50Warning.
  153. @property
  154. def _USE_L10N_INTERNAL(self):
  155. # Special hook to avoid checking a traceback in internal use on hot
  156. # paths.
  157. return self.__getattr__("USE_L10N")
  158. # RemovedInDjango51Warning.
  159. @property
  160. def DEFAULT_FILE_STORAGE(self):
  161. self._show_deprecation_warning(
  162. DEFAULT_FILE_STORAGE_DEPRECATED_MSG, RemovedInDjango51Warning
  163. )
  164. return self.__getattr__("DEFAULT_FILE_STORAGE")
  165. # RemovedInDjango51Warning.
  166. @property
  167. def STATICFILES_STORAGE(self):
  168. self._show_deprecation_warning(
  169. STATICFILES_STORAGE_DEPRECATED_MSG, RemovedInDjango51Warning
  170. )
  171. return self.__getattr__("STATICFILES_STORAGE")
  172. class Settings:
  173. def __init__(self, settings_module):
  174. # update this dict from global settings (but only for ALL_CAPS settings)
  175. for setting in dir(global_settings):
  176. if setting.isupper():
  177. setattr(self, setting, getattr(global_settings, setting))
  178. # store the settings module in case someone later cares
  179. self.SETTINGS_MODULE = settings_module
  180. mod = importlib.import_module(self.SETTINGS_MODULE)
  181. tuple_settings = (
  182. "ALLOWED_HOSTS",
  183. "INSTALLED_APPS",
  184. "TEMPLATE_DIRS",
  185. "LOCALE_PATHS",
  186. "SECRET_KEY_FALLBACKS",
  187. )
  188. self._explicit_settings = set()
  189. for setting in dir(mod):
  190. if setting.isupper():
  191. setting_value = getattr(mod, setting)
  192. if setting in tuple_settings and not isinstance(
  193. setting_value, (list, tuple)
  194. ):
  195. raise ImproperlyConfigured(
  196. "The %s setting must be a list or a tuple." % setting
  197. )
  198. setattr(self, setting, setting_value)
  199. self._explicit_settings.add(setting)
  200. if self.USE_TZ is False and not self.is_overridden("USE_TZ"):
  201. warnings.warn(
  202. "The default value of USE_TZ will change from False to True "
  203. "in Django 5.0. Set USE_TZ to False in your project settings "
  204. "if you want to keep the current default behavior.",
  205. category=RemovedInDjango50Warning,
  206. )
  207. if self.is_overridden("USE_DEPRECATED_PYTZ"):
  208. warnings.warn(USE_DEPRECATED_PYTZ_DEPRECATED_MSG, RemovedInDjango50Warning)
  209. if self.is_overridden("CSRF_COOKIE_MASKED"):
  210. warnings.warn(CSRF_COOKIE_MASKED_DEPRECATED_MSG, RemovedInDjango50Warning)
  211. if hasattr(time, "tzset") and self.TIME_ZONE:
  212. # When we can, attempt to validate the timezone. If we can't find
  213. # this file, no check happens and it's harmless.
  214. zoneinfo_root = Path("/usr/share/zoneinfo")
  215. zone_info_file = zoneinfo_root.joinpath(*self.TIME_ZONE.split("/"))
  216. if zoneinfo_root.exists() and not zone_info_file.exists():
  217. raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
  218. # Move the time zone info into os.environ. See ticket #2315 for why
  219. # we don't do this unconditionally (breaks Windows).
  220. os.environ["TZ"] = self.TIME_ZONE
  221. time.tzset()
  222. if self.is_overridden("USE_L10N"):
  223. warnings.warn(USE_L10N_DEPRECATED_MSG, RemovedInDjango50Warning)
  224. if self.is_overridden("DEFAULT_FILE_STORAGE"):
  225. if self.is_overridden("STORAGES"):
  226. raise ImproperlyConfigured(
  227. "DEFAULT_FILE_STORAGE/STORAGES are mutually exclusive."
  228. )
  229. self.STORAGES = {
  230. **self.STORAGES,
  231. DEFAULT_STORAGE_ALIAS: {"BACKEND": self.DEFAULT_FILE_STORAGE},
  232. }
  233. warnings.warn(DEFAULT_FILE_STORAGE_DEPRECATED_MSG, RemovedInDjango51Warning)
  234. if self.is_overridden("STATICFILES_STORAGE"):
  235. if self.is_overridden("STORAGES"):
  236. raise ImproperlyConfigured(
  237. "STATICFILES_STORAGE/STORAGES are mutually exclusive."
  238. )
  239. self.STORAGES = {
  240. **self.STORAGES,
  241. STATICFILES_STORAGE_ALIAS: {"BACKEND": self.STATICFILES_STORAGE},
  242. }
  243. warnings.warn(STATICFILES_STORAGE_DEPRECATED_MSG, RemovedInDjango51Warning)
  244. # RemovedInDjango51Warning.
  245. if self.is_overridden("STORAGES"):
  246. setattr(
  247. self,
  248. "DEFAULT_FILE_STORAGE",
  249. self.STORAGES.get(DEFAULT_STORAGE_ALIAS, {}).get("BACKEND"),
  250. )
  251. setattr(
  252. self,
  253. "STATICFILES_STORAGE",
  254. self.STORAGES.get(STATICFILES_STORAGE_ALIAS, {}).get("BACKEND"),
  255. )
  256. def is_overridden(self, setting):
  257. return setting in self._explicit_settings
  258. def __repr__(self):
  259. return '<%(cls)s "%(settings_module)s">' % {
  260. "cls": self.__class__.__name__,
  261. "settings_module": self.SETTINGS_MODULE,
  262. }
  263. class UserSettingsHolder:
  264. """Holder for user configured settings."""
  265. # SETTINGS_MODULE doesn't make much sense in the manually configured
  266. # (standalone) case.
  267. SETTINGS_MODULE = None
  268. def __init__(self, default_settings):
  269. """
  270. Requests for configuration variables not in this class are satisfied
  271. from the module specified in default_settings (if possible).
  272. """
  273. self.__dict__["_deleted"] = set()
  274. self.default_settings = default_settings
  275. def __getattr__(self, name):
  276. if not name.isupper() or name in self._deleted:
  277. raise AttributeError
  278. return getattr(self.default_settings, name)
  279. def __setattr__(self, name, value):
  280. self._deleted.discard(name)
  281. if name == "USE_L10N":
  282. warnings.warn(USE_L10N_DEPRECATED_MSG, RemovedInDjango50Warning)
  283. if name == "CSRF_COOKIE_MASKED":
  284. warnings.warn(CSRF_COOKIE_MASKED_DEPRECATED_MSG, RemovedInDjango50Warning)
  285. if name == "DEFAULT_FILE_STORAGE":
  286. self.STORAGES[DEFAULT_STORAGE_ALIAS] = {
  287. "BACKEND": self.DEFAULT_FILE_STORAGE
  288. }
  289. warnings.warn(DEFAULT_FILE_STORAGE_DEPRECATED_MSG, RemovedInDjango51Warning)
  290. if name == "STATICFILES_STORAGE":
  291. self.STORAGES[STATICFILES_STORAGE_ALIAS] = {
  292. "BACKEND": self.STATICFILES_STORAGE
  293. }
  294. warnings.warn(STATICFILES_STORAGE_DEPRECATED_MSG, RemovedInDjango51Warning)
  295. super().__setattr__(name, value)
  296. if name == "USE_DEPRECATED_PYTZ":
  297. warnings.warn(USE_DEPRECATED_PYTZ_DEPRECATED_MSG, RemovedInDjango50Warning)
  298. # RemovedInDjango51Warning.
  299. if name == "STORAGES":
  300. if default_file_storage := self.STORAGES.get(DEFAULT_STORAGE_ALIAS):
  301. super().__setattr__(
  302. "DEFAULT_FILE_STORAGE", default_file_storage.get("BACKEND")
  303. )
  304. else:
  305. self.STORAGES.setdefault(
  306. DEFAULT_STORAGE_ALIAS,
  307. {"BACKEND": "django.core.files.storage.FileSystemStorage"},
  308. )
  309. if staticfiles_storage := self.STORAGES.get(STATICFILES_STORAGE_ALIAS):
  310. super().__setattr__(
  311. "STATICFILES_STORAGE", staticfiles_storage.get("BACKEND")
  312. )
  313. else:
  314. self.STORAGES.setdefault(
  315. STATICFILES_STORAGE_ALIAS,
  316. {
  317. "BACKEND": (
  318. "django.contrib.staticfiles.storage.StaticFilesStorage"
  319. ),
  320. },
  321. )
  322. def __delattr__(self, name):
  323. self._deleted.add(name)
  324. if hasattr(self, name):
  325. super().__delattr__(name)
  326. def __dir__(self):
  327. return sorted(
  328. s
  329. for s in [*self.__dict__, *dir(self.default_settings)]
  330. if s not in self._deleted
  331. )
  332. def is_overridden(self, setting):
  333. deleted = setting in self._deleted
  334. set_locally = setting in self.__dict__
  335. set_on_default = getattr(
  336. self.default_settings, "is_overridden", lambda s: False
  337. )(setting)
  338. return deleted or set_locally or set_on_default
  339. def __repr__(self):
  340. return "<%(cls)s>" % {
  341. "cls": self.__class__.__name__,
  342. }
  343. settings = LazySettings()