Development of an internal social media platform with personalised dashboards for students
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 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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 warnings
  11. from pathlib import Path
  12. from django.conf import global_settings
  13. from django.core.exceptions import ImproperlyConfigured
  14. from django.utils.deprecation import RemovedInDjango30Warning
  15. from django.utils.functional import LazyObject, empty
  16. ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE"
  17. class LazySettings(LazyObject):
  18. """
  19. A lazy proxy for either global Django settings or a custom settings object.
  20. The user can manually configure settings prior to using them. Otherwise,
  21. Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE.
  22. """
  23. def _setup(self, name=None):
  24. """
  25. Load the settings module pointed to by the environment variable. This
  26. is used the first time settings are needed, if the user hasn't
  27. configured settings manually.
  28. """
  29. settings_module = os.environ.get(ENVIRONMENT_VARIABLE)
  30. if not settings_module:
  31. desc = ("setting %s" % name) if name else "settings"
  32. raise ImproperlyConfigured(
  33. "Requested %s, but settings are not configured. "
  34. "You must either define the environment variable %s "
  35. "or call settings.configure() before accessing settings."
  36. % (desc, ENVIRONMENT_VARIABLE))
  37. self._wrapped = Settings(settings_module)
  38. def __repr__(self):
  39. # Hardcode the class name as otherwise it yields 'Settings'.
  40. if self._wrapped is empty:
  41. return '<LazySettings [Unevaluated]>'
  42. return '<LazySettings "%(settings_module)s">' % {
  43. 'settings_module': self._wrapped.SETTINGS_MODULE,
  44. }
  45. def __getattr__(self, name):
  46. """Return the value of a setting and cache it in self.__dict__."""
  47. if self._wrapped is empty:
  48. self._setup(name)
  49. val = getattr(self._wrapped, name)
  50. self.__dict__[name] = val
  51. return val
  52. def __setattr__(self, name, value):
  53. """
  54. Set the value of setting. Clear all cached values if _wrapped changes
  55. (@override_settings does this) or clear single values when set.
  56. """
  57. if name == '_wrapped':
  58. self.__dict__.clear()
  59. else:
  60. self.__dict__.pop(name, None)
  61. super().__setattr__(name, value)
  62. def __delattr__(self, name):
  63. """Delete a setting and clear it from cache if needed."""
  64. super().__delattr__(name)
  65. self.__dict__.pop(name, None)
  66. def configure(self, default_settings=global_settings, **options):
  67. """
  68. Called to manually configure the settings. The 'default_settings'
  69. parameter sets where to retrieve any unspecified values from (its
  70. argument must support attribute access (__getattr__)).
  71. """
  72. if self._wrapped is not empty:
  73. raise RuntimeError('Settings already configured.')
  74. holder = UserSettingsHolder(default_settings)
  75. for name, value in options.items():
  76. setattr(holder, name, value)
  77. self._wrapped = holder
  78. @property
  79. def configured(self):
  80. """Return True if the settings have already been configured."""
  81. return self._wrapped is not empty
  82. class Settings:
  83. def __init__(self, settings_module):
  84. # update this dict from global settings (but only for ALL_CAPS settings)
  85. for setting in dir(global_settings):
  86. if setting.isupper():
  87. setattr(self, setting, getattr(global_settings, setting))
  88. # store the settings module in case someone later cares
  89. self.SETTINGS_MODULE = settings_module
  90. mod = importlib.import_module(self.SETTINGS_MODULE)
  91. tuple_settings = (
  92. "INSTALLED_APPS",
  93. "TEMPLATE_DIRS",
  94. "LOCALE_PATHS",
  95. )
  96. self._explicit_settings = set()
  97. for setting in dir(mod):
  98. if setting.isupper():
  99. setting_value = getattr(mod, setting)
  100. if (setting in tuple_settings and
  101. not isinstance(setting_value, (list, tuple))):
  102. raise ImproperlyConfigured("The %s setting must be a list or a tuple. " % setting)
  103. setattr(self, setting, setting_value)
  104. self._explicit_settings.add(setting)
  105. if not self.SECRET_KEY:
  106. raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
  107. if self.is_overridden('DEFAULT_CONTENT_TYPE'):
  108. warnings.warn('The DEFAULT_CONTENT_TYPE setting is deprecated.', RemovedInDjango30Warning)
  109. if hasattr(time, 'tzset') and self.TIME_ZONE:
  110. # When we can, attempt to validate the timezone. If we can't find
  111. # this file, no check happens and it's harmless.
  112. zoneinfo_root = Path('/usr/share/zoneinfo')
  113. zone_info_file = zoneinfo_root.joinpath(*self.TIME_ZONE.split('/'))
  114. if zoneinfo_root.exists() and not zone_info_file.exists():
  115. raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
  116. # Move the time zone info into os.environ. See ticket #2315 for why
  117. # we don't do this unconditionally (breaks Windows).
  118. os.environ['TZ'] = self.TIME_ZONE
  119. time.tzset()
  120. def is_overridden(self, setting):
  121. return setting in self._explicit_settings
  122. def __repr__(self):
  123. return '<%(cls)s "%(settings_module)s">' % {
  124. 'cls': self.__class__.__name__,
  125. 'settings_module': self.SETTINGS_MODULE,
  126. }
  127. class UserSettingsHolder:
  128. """Holder for user configured settings."""
  129. # SETTINGS_MODULE doesn't make much sense in the manually configured
  130. # (standalone) case.
  131. SETTINGS_MODULE = None
  132. def __init__(self, default_settings):
  133. """
  134. Requests for configuration variables not in this class are satisfied
  135. from the module specified in default_settings (if possible).
  136. """
  137. self.__dict__['_deleted'] = set()
  138. self.default_settings = default_settings
  139. def __getattr__(self, name):
  140. if name in self._deleted:
  141. raise AttributeError
  142. return getattr(self.default_settings, name)
  143. def __setattr__(self, name, value):
  144. self._deleted.discard(name)
  145. if name == 'DEFAULT_CONTENT_TYPE':
  146. warnings.warn('The DEFAULT_CONTENT_TYPE setting is deprecated.', RemovedInDjango30Warning)
  147. super().__setattr__(name, value)
  148. def __delattr__(self, name):
  149. self._deleted.add(name)
  150. if hasattr(self, name):
  151. super().__delattr__(name)
  152. def __dir__(self):
  153. return sorted(
  154. s for s in list(self.__dict__) + dir(self.default_settings)
  155. if s not in self._deleted
  156. )
  157. def is_overridden(self, setting):
  158. deleted = (setting in self._deleted)
  159. set_locally = (setting in self.__dict__)
  160. set_on_default = getattr(self.default_settings, 'is_overridden', lambda s: False)(setting)
  161. return deleted or set_locally or set_on_default
  162. def __repr__(self):
  163. return '<%(cls)s>' % {
  164. 'cls': self.__class__.__name__,
  165. }
  166. settings = LazySettings()