summaryrefslogtreecommitdiff
path: root/django/conf/__init__.py
diff options
context:
space:
mode:
Diffstat (limited to 'django/conf/__init__.py')
-rw-r--r--django/conf/__init__.py105
1 files changed, 58 insertions, 47 deletions
diff --git a/django/conf/__init__.py b/django/conf/__init__.py
index 05345cb6e9..e1fb7f973f 100644
--- a/django/conf/__init__.py
+++ b/django/conf/__init__.py
@@ -23,20 +23,20 @@ ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE"
# RemovedInDjango50Warning
USE_DEPRECATED_PYTZ_DEPRECATED_MSG = (
- 'The USE_DEPRECATED_PYTZ setting, and support for pytz timezones is '
- 'deprecated in favor of the stdlib zoneinfo module. Please update your '
- 'code to use zoneinfo and remove the USE_DEPRECATED_PYTZ setting.'
+ "The USE_DEPRECATED_PYTZ setting, and support for pytz timezones is "
+ "deprecated in favor of the stdlib zoneinfo module. Please update your "
+ "code to use zoneinfo and remove the USE_DEPRECATED_PYTZ setting."
)
USE_L10N_DEPRECATED_MSG = (
- 'The USE_L10N setting is deprecated. Starting with Django 5.0, localized '
- 'formatting of data will always be enabled. For example Django will '
- 'display numbers and dates using the format of the current locale.'
+ "The USE_L10N setting is deprecated. Starting with Django 5.0, localized "
+ "formatting of data will always be enabled. For example Django will "
+ "display numbers and dates using the format of the current locale."
)
CSRF_COOKIE_MASKED_DEPRECATED_MSG = (
- 'The CSRF_COOKIE_MASKED transitional setting is deprecated. Support for '
- 'it will be removed in Django 5.0.'
+ "The CSRF_COOKIE_MASKED transitional setting is deprecated. Support for "
+ "it will be removed in Django 5.0."
)
@@ -45,6 +45,7 @@ class SettingsReference(str):
String subclass which references a current settings value. It's treated as
the value in memory but serializes to a settings.NAME attribute reference.
"""
+
def __new__(self, value, setting_name):
return str.__new__(self, value)
@@ -58,6 +59,7 @@ class LazySettings(LazyObject):
The user can manually configure settings prior to using them. Otherwise,
Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE.
"""
+
def _setup(self, name=None):
"""
Load the settings module pointed to by the environment variable. This
@@ -71,16 +73,17 @@ class LazySettings(LazyObject):
"Requested %s, but settings are not configured. "
"You must either define the environment variable %s "
"or call settings.configure() before accessing settings."
- % (desc, ENVIRONMENT_VARIABLE))
+ % (desc, ENVIRONMENT_VARIABLE)
+ )
self._wrapped = Settings(settings_module)
def __repr__(self):
# Hardcode the class name as otherwise it yields 'Settings'.
if self._wrapped is empty:
- return '<LazySettings [Unevaluated]>'
+ return "<LazySettings [Unevaluated]>"
return '<LazySettings "%(settings_module)s">' % {
- 'settings_module': self._wrapped.SETTINGS_MODULE,
+ "settings_module": self._wrapped.SETTINGS_MODULE,
}
def __getattr__(self, name):
@@ -91,9 +94,9 @@ class LazySettings(LazyObject):
# Special case some settings which require further modification.
# This is done here for performance reasons so the modified value is cached.
- if name in {'MEDIA_URL', 'STATIC_URL'} and val is not None:
+ if name in {"MEDIA_URL", "STATIC_URL"} and val is not None:
val = self._add_script_prefix(val)
- elif name == 'SECRET_KEY' and not val:
+ elif name == "SECRET_KEY" and not val:
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
self.__dict__[name] = val
@@ -104,7 +107,7 @@ class LazySettings(LazyObject):
Set the value of setting. Clear all cached values if _wrapped changes
(@override_settings does this) or clear single values when set.
"""
- if name == '_wrapped':
+ if name == "_wrapped":
self.__dict__.clear()
else:
self.__dict__.pop(name, None)
@@ -122,11 +125,11 @@ class LazySettings(LazyObject):
argument must support attribute access (__getattr__)).
"""
if self._wrapped is not empty:
- raise RuntimeError('Settings already configured.')
+ raise RuntimeError("Settings already configured.")
holder = UserSettingsHolder(default_settings)
for name, value in options.items():
if not name.isupper():
- raise TypeError('Setting %r must be uppercase.' % name)
+ raise TypeError("Setting %r must be uppercase." % name)
setattr(holder, name, value)
self._wrapped = holder
@@ -139,10 +142,11 @@ class LazySettings(LazyObject):
subpath to STATIC_URL and MEDIA_URL in settings is inconvenient.
"""
# Don't apply prefix to absolute paths and URLs.
- if value.startswith(('http://', 'https://', '/')):
+ if value.startswith(("http://", "https://", "/")):
return value
from django.urls import get_script_prefix
- return '%s%s' % (get_script_prefix(), value)
+
+ return "%s%s" % (get_script_prefix(), value)
@property
def configured(self):
@@ -161,14 +165,14 @@ class LazySettings(LazyObject):
RemovedInDjango50Warning,
stacklevel=2,
)
- return self.__getattr__('USE_L10N')
+ return self.__getattr__("USE_L10N")
# RemovedInDjango50Warning.
@property
def _USE_L10N_INTERNAL(self):
# Special hook to avoid checking a traceback in internal use on hot
# paths.
- return self.__getattr__('USE_L10N')
+ return self.__getattr__("USE_L10N")
class Settings:
@@ -184,7 +188,7 @@ class Settings:
mod = importlib.import_module(self.SETTINGS_MODULE)
tuple_settings = (
- 'ALLOWED_HOSTS',
+ "ALLOWED_HOSTS",
"INSTALLED_APPS",
"TEMPLATE_DIRS",
"LOCALE_PATHS",
@@ -195,39 +199,42 @@ class Settings:
if setting.isupper():
setting_value = getattr(mod, setting)
- if (setting in tuple_settings and
- not isinstance(setting_value, (list, tuple))):
- raise ImproperlyConfigured("The %s setting must be a list or a tuple." % setting)
+ if setting in tuple_settings and not isinstance(
+ setting_value, (list, tuple)
+ ):
+ raise ImproperlyConfigured(
+ "The %s setting must be a list or a tuple." % setting
+ )
setattr(self, setting, setting_value)
self._explicit_settings.add(setting)
- if self.USE_TZ is False and not self.is_overridden('USE_TZ'):
+ if self.USE_TZ is False and not self.is_overridden("USE_TZ"):
warnings.warn(
- 'The default value of USE_TZ will change from False to True '
- 'in Django 5.0. Set USE_TZ to False in your project settings '
- 'if you want to keep the current default behavior.',
+ "The default value of USE_TZ will change from False to True "
+ "in Django 5.0. Set USE_TZ to False in your project settings "
+ "if you want to keep the current default behavior.",
category=RemovedInDjango50Warning,
)
- if self.is_overridden('USE_DEPRECATED_PYTZ'):
+ if self.is_overridden("USE_DEPRECATED_PYTZ"):
warnings.warn(USE_DEPRECATED_PYTZ_DEPRECATED_MSG, RemovedInDjango50Warning)
- if self.is_overridden('CSRF_COOKIE_MASKED'):
+ if self.is_overridden("CSRF_COOKIE_MASKED"):
warnings.warn(CSRF_COOKIE_MASKED_DEPRECATED_MSG, RemovedInDjango50Warning)
- if hasattr(time, 'tzset') and self.TIME_ZONE:
+ if hasattr(time, "tzset") and self.TIME_ZONE:
# When we can, attempt to validate the timezone. If we can't find
# this file, no check happens and it's harmless.
- zoneinfo_root = Path('/usr/share/zoneinfo')
- zone_info_file = zoneinfo_root.joinpath(*self.TIME_ZONE.split('/'))
+ zoneinfo_root = Path("/usr/share/zoneinfo")
+ zone_info_file = zoneinfo_root.joinpath(*self.TIME_ZONE.split("/"))
if zoneinfo_root.exists() and not zone_info_file.exists():
raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
# Move the time zone info into os.environ. See ticket #2315 for why
# we don't do this unconditionally (breaks Windows).
- os.environ['TZ'] = self.TIME_ZONE
+ os.environ["TZ"] = self.TIME_ZONE
time.tzset()
- if self.is_overridden('USE_L10N'):
+ if self.is_overridden("USE_L10N"):
warnings.warn(USE_L10N_DEPRECATED_MSG, RemovedInDjango50Warning)
def is_overridden(self, setting):
@@ -235,13 +242,14 @@ class Settings:
def __repr__(self):
return '<%(cls)s "%(settings_module)s">' % {
- 'cls': self.__class__.__name__,
- 'settings_module': self.SETTINGS_MODULE,
+ "cls": self.__class__.__name__,
+ "settings_module": self.SETTINGS_MODULE,
}
class UserSettingsHolder:
"""Holder for user configured settings."""
+
# SETTINGS_MODULE doesn't make much sense in the manually configured
# (standalone) case.
SETTINGS_MODULE = None
@@ -251,7 +259,7 @@ class UserSettingsHolder:
Requests for configuration variables not in this class are satisfied
from the module specified in default_settings (if possible).
"""
- self.__dict__['_deleted'] = set()
+ self.__dict__["_deleted"] = set()
self.default_settings = default_settings
def __getattr__(self, name):
@@ -261,12 +269,12 @@ class UserSettingsHolder:
def __setattr__(self, name, value):
self._deleted.discard(name)
- if name == 'USE_L10N':
+ if name == "USE_L10N":
warnings.warn(USE_L10N_DEPRECATED_MSG, RemovedInDjango50Warning)
- if name == 'CSRF_COOKIE_MASKED':
+ if name == "CSRF_COOKIE_MASKED":
warnings.warn(CSRF_COOKIE_MASKED_DEPRECATED_MSG, RemovedInDjango50Warning)
super().__setattr__(name, value)
- if name == 'USE_DEPRECATED_PYTZ':
+ if name == "USE_DEPRECATED_PYTZ":
warnings.warn(USE_DEPRECATED_PYTZ_DEPRECATED_MSG, RemovedInDjango50Warning)
def __delattr__(self, name):
@@ -276,19 +284,22 @@ class UserSettingsHolder:
def __dir__(self):
return sorted(
- s for s in [*self.__dict__, *dir(self.default_settings)]
+ s
+ for s in [*self.__dict__, *dir(self.default_settings)]
if s not in self._deleted
)
def is_overridden(self, setting):
- deleted = (setting in self._deleted)
- set_locally = (setting in self.__dict__)
- set_on_default = getattr(self.default_settings, 'is_overridden', lambda s: False)(setting)
+ deleted = setting in self._deleted
+ set_locally = setting in self.__dict__
+ set_on_default = getattr(
+ self.default_settings, "is_overridden", lambda s: False
+ )(setting)
return deleted or set_locally or set_on_default
def __repr__(self):
- return '<%(cls)s>' % {
- 'cls': self.__class__.__name__,
+ return "<%(cls)s>" % {
+ "cls": self.__class__.__name__,
}