Debian Codegraph @

django/conf/__init__.py

raw
1 """
2 Settings and configuration for Django.
3
4 Read values from the module specified by the DJANGO_SETTINGS_MODULE environment
5 variable, and then from django.conf.global_settings; see the global_settings.py
6 for a list of all possible variables.
7 """
8
9 import importlib
10 import os
11 import time
12 import traceback
13 import warnings
14 from pathlib import Path
15
16 import django
17 from django.conf import global_settings
18 from django.core.exceptions import ImproperlyConfigured
19 from django.utils.deprecation import RemovedInDjango60Warning
20 from django.utils.functional import LazyObject, empty
21
22 ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE"
23 DEFAULT_STORAGE_ALIAS = "default"
24 STATICFILES_STORAGE_ALIAS = "staticfiles"
25
26 # RemovedInDjango60Warning.
27 FORMS_URLFIELD_ASSUME_HTTPS_DEPRECATED_MSG = (
28 "The FORMS_URLFIELD_ASSUME_HTTPS transitional setting is deprecated."
29 )
30
31
32 class SettingsReference(str):
33 """
34 String subclass which references a current settings value. It's treated as
35 the value in memory but serializes to a settings.NAME attribute reference.
36 """
37
38 def __new__(self, value, setting_name):
39 return str.__new__(self, value)
40
41 def __init__(self, value, setting_name):
42 self.setting_name = setting_name
43
44
45 class LazySettings(LazyObject):
46 """
47 A lazy proxy for either global Django settings or a custom settings object.
48 The user can manually configure settings prior to using them. Otherwise,
49 Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE.
50 """
51
52 def _setup(self, name=None):
53 """
54 Load the settings module pointed to by the environment variable. This
55 is used the first time settings are needed, if the user hasn't
56 configured settings manually.
57 """
58 settings_module = os.environ.get(ENVIRONMENT_VARIABLE)
59 if not settings_module:
60 desc = ("setting %s" % name) if name else "settings"
61 raise ImproperlyConfigured(
62 "Requested %s, but settings are not configured. "
63 "You must either define the environment variable %s "
64 "or call settings.configure() before accessing settings."
65 % (desc, ENVIRONMENT_VARIABLE)
66 )
67
68 self._wrapped = Settings(settings_module)
69
70 def __repr__(self):
71 # Hardcode the class name as otherwise it yields 'Settings'.
72 if self._wrapped is empty:
73 return "<LazySettings [Unevaluated]>"
74 return '<LazySettings "%(settings_module)s">' % {
75 "settings_module": self._wrapped.SETTINGS_MODULE,
76 }
77
78 def __getattr__(self, name):
79 """Return the value of a setting and cache it in self.__dict__."""
80 if (_wrapped := self._wrapped) is empty:
81 self._setup(name)
82 _wrapped = self._wrapped
83 val = getattr(_wrapped, name)
84
85 # Special case some settings which require further modification.
86 # This is done here for performance reasons so the modified value is cached.
87 if name in {"MEDIA_URL", "STATIC_URL"} and val is not None:
88 val = self._add_script_prefix(val)
89 elif name == "SECRET_KEY" and not val:
90 raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
91
92 self.__dict__[name] = val
93 return val
94
95 def __setattr__(self, name, value):
96 """
97 Set the value of setting. Clear all cached values if _wrapped changes
98 (@override_settings does this) or clear single values when set.
99 """
100 if name == "_wrapped":
101 self.__dict__.clear()
102 else:
103 self.__dict__.pop(name, None)
104 super().__setattr__(name, value)
105
106 def __delattr__(self, name):
107 """Delete a setting and clear it from cache if needed."""
108 super().__delattr__(name)
109 self.__dict__.pop(name, None)
110
111 def configure(self, default_settings=global_settings, **options):
112 """
113 Called to manually configure the settings. The 'default_settings'
114 parameter sets where to retrieve any unspecified values from (its
115 argument must support attribute access (__getattr__)).
116 """
117 if self._wrapped is not empty:
118 raise RuntimeError("Settings already configured.")
119 holder = UserSettingsHolder(default_settings)
120 for name, value in options.items():
121 if not name.isupper():
122 raise TypeError("Setting %r must be uppercase." % name)
123 setattr(holder, name, value)
124 self._wrapped = holder
125
126 @staticmethod
127 def _add_script_prefix(value):
128 """
129 Add SCRIPT_NAME prefix to relative paths.
130
131 Useful when the app is being served at a subpath and manually prefixing
132 subpath to STATIC_URL and MEDIA_URL in settings is inconvenient.
133 """
134 # Don't apply prefix to absolute paths and URLs.
135 if value.startswith(("http://", "https://", "/")):
136 return value
137 from django.urls import get_script_prefix
138
139 return "%s%s" % (get_script_prefix(), value)
140
141 @property
142 def configured(self):
143 """Return True if the settings have already been configured."""
144 return self._wrapped is not empty
145
146 def _show_deprecation_warning(self, message, category):
147 stack = traceback.extract_stack()
148 # Show a warning if the setting is used outside of Django.
149 # Stack index: -1 this line, -2 the property, -3 the
150 # LazyObject __getattribute__(), -4 the caller.
151 filename, _, _, _ = stack[-4]
152 if not filename.startswith(os.path.dirname(django.__file__)):
153 warnings.warn(message, category, stacklevel=2)
154
155
156 class Settings:
157 def __init__(self, settings_module):
158 # update this dict from global settings (but only for ALL_CAPS settings)
159 for setting in dir(global_settings):
160 if setting.isupper():
161 setattr(self, setting, getattr(global_settings, setting))
162
163 # store the settings module in case someone later cares
164 self.SETTINGS_MODULE = settings_module
165
166 mod = importlib.import_module(self.SETTINGS_MODULE)
167
168 tuple_settings = (
169 "ALLOWED_HOSTS",
170 "INSTALLED_APPS",
171 "TEMPLATE_DIRS",
172 "LOCALE_PATHS",
173 "SECRET_KEY_FALLBACKS",
174 )
175 self._explicit_settings = set()
176 for setting in dir(mod):
177 if setting.isupper():
178 setting_value = getattr(mod, setting)
179
180 if setting in tuple_settings and not isinstance(
181 setting_value, (list, tuple)
182 ):
183 raise ImproperlyConfigured(
184 "The %s setting must be a list or a tuple." % setting
185 )
186 setattr(self, setting, setting_value)
187 self._explicit_settings.add(setting)
188
189 if self.is_overridden("FORMS_URLFIELD_ASSUME_HTTPS"):
190 warnings.warn(
191 FORMS_URLFIELD_ASSUME_HTTPS_DEPRECATED_MSG,
192 RemovedInDjango60Warning,
193 )
194
195 if hasattr(time, "tzset") and self.TIME_ZONE:
196 # When we can, attempt to validate the timezone. If we can't find
197 # this file, no check happens and it's harmless.
198 zoneinfo_root = Path("/usr/share/zoneinfo")
199 zone_info_file = zoneinfo_root.joinpath(*self.TIME_ZONE.split("/"))
200 if zoneinfo_root.exists() and not zone_info_file.exists():
201 raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
202 # Move the time zone info into os.environ. See ticket #2315 for why
203 # we don't do this unconditionally (breaks Windows).
204 os.environ["TZ"] = self.TIME_ZONE
205 time.tzset()
206
207 def is_overridden(self, setting):
208 return setting in self._explicit_settings
209
210 def __repr__(self):
211 return '<%(cls)s "%(settings_module)s">' % {
212 "cls": self.__class__.__name__,
213 "settings_module": self.SETTINGS_MODULE,
214 }
215
216
217 class UserSettingsHolder:
218 """Holder for user configured settings."""
219
220 # SETTINGS_MODULE doesn't make much sense in the manually configured
221 # (standalone) case.
222 SETTINGS_MODULE = None
223
224 def __init__(self, default_settings):
225 """
226 Requests for configuration variables not in this class are satisfied
227 from the module specified in default_settings (if possible).
228 """
229 self.__dict__["_deleted"] = set()
230 self.default_settings = default_settings
231
232 def __getattr__(self, name):
233 if not name.isupper() or name in self._deleted:
234 raise AttributeError
235 return getattr(self.default_settings, name)
236
237 def __setattr__(self, name, value):
238 self._deleted.discard(name)
239 if name == "FORMS_URLFIELD_ASSUME_HTTPS":
240 warnings.warn(
241 FORMS_URLFIELD_ASSUME_HTTPS_DEPRECATED_MSG,
242 RemovedInDjango60Warning,
243 )
244 super().__setattr__(name, value)
245
246 def __delattr__(self, name):
247 self._deleted.add(name)
248 if hasattr(self, name):
249 super().__delattr__(name)
250
251 def __dir__(self):
252 return sorted(
253 s
254 for s in [*self.__dict__, *dir(self.default_settings)]
255 if s not in self._deleted
256 )
257
258 def is_overridden(self, setting):
259 deleted = setting in self._deleted
260 set_locally = setting in self.__dict__
261 set_on_default = getattr(
262 self.default_settings, "is_overridden", lambda s: False
263 )(setting)
264 return deleted or set_locally or set_on_default
265
266 def __repr__(self):
267 return "<%(cls)s>" % {
268 "cls": self.__class__.__name__,
269 }
270
271
272 settings = LazySettings()