config.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # pylint: disable=missing-module-docstring
  3. from __future__ import annotations
  4. import pathlib
  5. from pydantic import BaseModel
  6. from searx.compat import tomllib
  7. from .cache import FaviconCacheConfig
  8. from .proxy import FaviconProxyConfig
  9. CONFIG_SCHEMA: int = 1
  10. """Version of the configuration schema."""
  11. TOML_CACHE_CFG: dict[str, "FaviconConfig"] = {}
  12. """Cache config objects by TOML's filename."""
  13. DEFAULT_CFG_TOML_PATH = pathlib.Path(__file__).parent / "favicons.toml"
  14. class FaviconConfig(BaseModel):
  15. """The class aggregates configurations of the favicon tools"""
  16. cfg_schema: int
  17. """Config's schema version. The specification of the version of the schema
  18. is mandatory, currently only version :py:obj:`CONFIG_SCHEMA` is supported.
  19. By specifying a version, it is possible to ensure downward compatibility in
  20. the event of future changes to the configuration schema"""
  21. cache: FaviconCacheConfig = FaviconCacheConfig()
  22. """Setup of the :py:obj:`.cache.FaviconCacheConfig`."""
  23. proxy: FaviconProxyConfig = FaviconProxyConfig()
  24. """Setup of the :py:obj:`.proxy.FaviconProxyConfig`."""
  25. @classmethod
  26. def from_toml_file(cls, cfg_file: pathlib.Path, use_cache: bool) -> "FaviconConfig":
  27. """Create a config object from a TOML file, the ``use_cache`` argument
  28. specifies whether a cache should be used.
  29. """
  30. cached = TOML_CACHE_CFG.get(str(cfg_file))
  31. if use_cache and cached:
  32. return cached
  33. with cfg_file.open("rb") as f:
  34. cfg = tomllib.load(f)
  35. cfg = cfg.get("favicons", cfg)
  36. schema = cfg.get("cfg_schema")
  37. if schema != CONFIG_SCHEMA:
  38. raise ValueError(
  39. f"config schema version {CONFIG_SCHEMA} is needed, version {schema} is given in {cfg_file}"
  40. )
  41. cfg = cls(**cfg)
  42. if use_cache and cached:
  43. TOML_CACHE_CFG[str(cfg_file.resolve())] = cfg
  44. return cfg