currencies.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Simple implementation to store currencies data in a SQL database."""
  3. from __future__ import annotations
  4. __all__ = ["CurrenciesDB"]
  5. import json
  6. import pathlib
  7. from .core import get_cache, log
  8. class CurrenciesDB:
  9. # pylint: disable=missing-class-docstring
  10. ctx_names = "data_currencies_names"
  11. ctx_iso4217 = "data_currencies_iso4217"
  12. json_file = pathlib.Path(__file__).parent / "currencies.json"
  13. def __init__(self):
  14. self.cache = get_cache()
  15. def init(self):
  16. if self.cache.properties("currencies loaded") != "OK":
  17. self.load()
  18. self.cache.properties.set("currencies loaded", "OK")
  19. # F I X M E:
  20. # do we need a maintenance .. rember: database is stored
  21. # in /tmp and will be rebuild during the reboot anyway
  22. def load(self):
  23. log.debug("init searx.data.CURRENCIES")
  24. with open(self.json_file, encoding="utf-8") as f:
  25. data_dict = json.load(f)
  26. for key, value in data_dict["names"].items():
  27. self.cache.set(key=key, value=value, ctx=self.ctx_names, expire=None)
  28. for key, value in data_dict["iso4217"].items():
  29. self.cache.set(key=key, value=value, ctx=self.ctx_iso4217, expire=None)
  30. def name_to_iso4217(self, name):
  31. self.init()
  32. ret_val = self.cache.get(key=name, default=name, ctx=self.ctx_names)
  33. if isinstance(ret_val, list):
  34. # if more alternatives, use the last in the list
  35. ret_val = ret_val[-1]
  36. return ret_val
  37. def iso4217_to_name(self, iso4217, language):
  38. self.init()
  39. iso4217_languages: dict = self.cache.get(key=iso4217, default={}, ctx=self.ctx_iso4217)
  40. return iso4217_languages.get(language, iso4217)