beaker_cache.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # ext/beaker_cache.py
  2. # Copyright 2006-2025 the Mako authors and contributors <see AUTHORS file>
  3. #
  4. # This module is part of Mako and is released under
  5. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  6. """Provide a :class:`.CacheImpl` for the Beaker caching system."""
  7. from mako import exceptions
  8. from mako.cache import CacheImpl
  9. try:
  10. from beaker import cache as beaker_cache
  11. except:
  12. has_beaker = False
  13. else:
  14. has_beaker = True
  15. _beaker_cache = None
  16. class BeakerCacheImpl(CacheImpl):
  17. """A :class:`.CacheImpl` provided for the Beaker caching system.
  18. This plugin is used by default, based on the default
  19. value of ``'beaker'`` for the ``cache_impl`` parameter of the
  20. :class:`.Template` or :class:`.TemplateLookup` classes.
  21. """
  22. def __init__(self, cache):
  23. if not has_beaker:
  24. raise exceptions.RuntimeException(
  25. "Can't initialize Beaker plugin; Beaker is not installed."
  26. )
  27. global _beaker_cache
  28. if _beaker_cache is None:
  29. if "manager" in cache.template.cache_args:
  30. _beaker_cache = cache.template.cache_args["manager"]
  31. else:
  32. _beaker_cache = beaker_cache.CacheManager()
  33. super().__init__(cache)
  34. def _get_cache(self, **kw):
  35. expiretime = kw.pop("timeout", None)
  36. if "dir" in kw:
  37. kw["data_dir"] = kw.pop("dir")
  38. elif self.cache.template.module_directory:
  39. kw["data_dir"] = self.cache.template.module_directory
  40. if "manager" in kw:
  41. kw.pop("manager")
  42. if kw.get("type") == "memcached":
  43. kw["type"] = "ext:memcached"
  44. if "region" in kw:
  45. region = kw.pop("region")
  46. cache = _beaker_cache.get_cache_region(self.cache.id, region, **kw)
  47. else:
  48. cache = _beaker_cache.get_cache(self.cache.id, **kw)
  49. cache_args = {"starttime": self.cache.starttime}
  50. if expiretime:
  51. cache_args["expiretime"] = expiretime
  52. return cache, cache_args
  53. def get_or_create(self, key, creation_function, **kw):
  54. cache, kw = self._get_cache(**kw)
  55. return cache.get(key, createfunc=creation_function, **kw)
  56. def put(self, key, value, **kw):
  57. cache, kw = self._get_cache(**kw)
  58. cache.put(key, value, **kw)
  59. def get(self, key, **kw):
  60. cache, kw = self._get_cache(**kw)
  61. return cache.get(key, **kw)
  62. def invalidate(self, key, **kw):
  63. cache, kw = self._get_cache(**kw)
  64. cache.remove_value(key, **kw)