Skip to content

Commit

Permalink
refactor!(settings): Simplify settings structure
Browse files Browse the repository at this point in the history
  • Loading branch information
tony committed Oct 15, 2022
1 parent 77b980c commit c75515f
Showing 1 changed file with 37 additions and 16 deletions.
53 changes: 37 additions & 16 deletions src/robots/settings.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,44 @@
import sys
import typing as t

from django.conf import settings
from django.test.signals import setting_changed

class Settings:
defaults = {
#: A list of one or more sitemaps to inform robots about:
"SITEMAP_URLS": ("ROBOTS_SITEMAP_URLS", []),
"USE_SITEMAP": ("ROBOTS_USE_SITEMAP", True),
"USE_HOST": ("ROBOTS_USE_HOST", True),
"CACHE_TIMEOUT": ("ROBOTS_CACHE_TIMEOUT", None),
"SITE_BY_REQUEST": ("ROBOTS_SITE_BY_REQUEST", False),
"USE_SCHEME_IN_HOST": ("ROBOTS_USE_SCHEME_IN_HOST", False),
"SITEMAP_VIEW_NAME": ("ROBOTS_SITEMAP_VIEW_NAME", False),
}
DEFAULT_ROBOTS_SETTINGS: t.Dict[str, t.Any] = {
"SITEMAP_URLS": [],
"USE_SITEMAP": True,
"USE_HOST": True,
"CACHE_TIMEOUT": None,
"SITE_BY_REQUEST": False,
"USE_SCHEME_IN_HOST": False,
"SITEMAP_VIEW_NAME": False,
}

def __getattr__(self, attribute):
from django.conf import settings

if attribute in self.defaults:
return getattr(settings, *self.defaults[attribute])
def getdefault(setting: str) -> t.Any:
return getattr(settings, f"ROBOTS_{setting}", DEFAULT_ROBOTS_SETTINGS[setting])


sys.modules[__name__] = Settings()
SITEMAP_URLS: t.List[str] = getdefault("SITEMAP_URLS")
USE_SITEMAP: bool = getdefault("USE_SITEMAP")
USE_HOST: bool = getdefault("USE_HOST")
CACHE_TIMEOUT: t.Optional[int] = getdefault("CACHE_TIMEOUT")
SITE_BY_REQUEST: bool = getdefault("SITE_BY_REQUEST")
USE_SCHEME_IN_HOST: bool = getdefault("USE_SCHEME_IN_HOST")
SITEMAP_VIEW_NAME: bool = getdefault("SITEMAP_VIEW_NAME")


def reload_robots_settings(
setting: str, value: t.Any, enter: bool, **kwargs: object
) -> None:
if not setting.startswith("ROBOTS_"): # pragma: no cover
return

setting = setting.replace("ROBOTS_", "")
if enter: # setting applied
setattr(sys.modules[__name__], setting, value)
else:
setattr(sys.modules[__name__], setting, getdefault(setting))


setting_changed.connect(reload_robots_settings)

0 comments on commit c75515f

Please sign in to comment.