currencies.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. # To avoid parallel initializations, the property is set first
  18. self.cache.properties.set("currencies loaded", "OK")
  19. self.load()
  20. # F I X M E:
  21. # do we need a maintenance .. rember: database is stored
  22. # in /tmp and will be rebuild during the reboot anyway
  23. def load(self):
  24. log.debug("init searx.data.CURRENCIES")
  25. with open(self.json_file, encoding="utf-8") as f:
  26. data_dict = json.load(f)
  27. for key, value in data_dict["names"].items():
  28. self.cache.set(key=key, value=value, ctx=self.ctx_names, expire=None)
  29. for key, value in data_dict["iso4217"].items():
  30. self.cache.set(key=key, value=value, ctx=self.ctx_iso4217, expire=None)
  31. def name_to_iso4217(self, name):
  32. self.init()
  33. ret_val = self.cache.get(key=name, default=name, ctx=self.ctx_names)
  34. if isinstance(ret_val, list):
  35. # if more alternatives, use the last in the list
  36. ret_val = ret_val[-1]
  37. return ret_val
  38. def iso4217_to_name(self, iso4217, language):
  39. self.init()
  40. iso4217_languages: dict = self.cache.get(key=iso4217, default={}, ctx=self.ctx_iso4217)
  41. return iso4217_languages.get(language, iso4217)