cache.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. # mako/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. from mako import util
  7. _cache_plugins = util.PluginLoader("mako.cache")
  8. register_plugin = _cache_plugins.register
  9. register_plugin("beaker", "mako.ext.beaker_cache", "BeakerCacheImpl")
  10. class Cache:
  11. """Represents a data content cache made available to the module
  12. space of a specific :class:`.Template` object.
  13. .. versionadded:: 0.6
  14. :class:`.Cache` by itself is mostly a
  15. container for a :class:`.CacheImpl` object, which implements
  16. a fixed API to provide caching services; specific subclasses exist to
  17. implement different
  18. caching strategies. Mako includes a backend that works with
  19. the Beaker caching system. Beaker itself then supports
  20. a number of backends (i.e. file, memory, memcached, etc.)
  21. The construction of a :class:`.Cache` is part of the mechanics
  22. of a :class:`.Template`, and programmatic access to this
  23. cache is typically via the :attr:`.Template.cache` attribute.
  24. """
  25. impl = None
  26. """Provide the :class:`.CacheImpl` in use by this :class:`.Cache`.
  27. This accessor allows a :class:`.CacheImpl` with additional
  28. methods beyond that of :class:`.Cache` to be used programmatically.
  29. """
  30. id = None
  31. """Return the 'id' that identifies this cache.
  32. This is a value that should be globally unique to the
  33. :class:`.Template` associated with this cache, and can
  34. be used by a caching system to name a local container
  35. for data specific to this template.
  36. """
  37. starttime = None
  38. """Epochal time value for when the owning :class:`.Template` was
  39. first compiled.
  40. A cache implementation may wish to invalidate data earlier than
  41. this timestamp; this has the effect of the cache for a specific
  42. :class:`.Template` starting clean any time the :class:`.Template`
  43. is recompiled, such as when the original template file changed on
  44. the filesystem.
  45. """
  46. def __init__(self, template, *args):
  47. # check for a stale template calling the
  48. # constructor
  49. if isinstance(template, str) and args:
  50. return
  51. self.template = template
  52. self.id = template.module.__name__
  53. self.starttime = template.module._modified_time
  54. self._def_regions = {}
  55. self.impl = self._load_impl(self.template.cache_impl)
  56. def _load_impl(self, name):
  57. return _cache_plugins.load(name)(self)
  58. def get_or_create(self, key, creation_function, **kw):
  59. """Retrieve a value from the cache, using the given creation function
  60. to generate a new value."""
  61. return self._ctx_get_or_create(key, creation_function, None, **kw)
  62. def _ctx_get_or_create(self, key, creation_function, context, **kw):
  63. """Retrieve a value from the cache, using the given creation function
  64. to generate a new value."""
  65. if not self.template.cache_enabled:
  66. return creation_function()
  67. return self.impl.get_or_create(
  68. key, creation_function, **self._get_cache_kw(kw, context)
  69. )
  70. def set(self, key, value, **kw):
  71. r"""Place a value in the cache.
  72. :param key: the value's key.
  73. :param value: the value.
  74. :param \**kw: cache configuration arguments.
  75. """
  76. self.impl.set(key, value, **self._get_cache_kw(kw, None))
  77. put = set
  78. """A synonym for :meth:`.Cache.set`.
  79. This is here for backwards compatibility.
  80. """
  81. def get(self, key, **kw):
  82. r"""Retrieve a value from the cache.
  83. :param key: the value's key.
  84. :param \**kw: cache configuration arguments. The
  85. backend is configured using these arguments upon first request.
  86. Subsequent requests that use the same series of configuration
  87. values will use that same backend.
  88. """
  89. return self.impl.get(key, **self._get_cache_kw(kw, None))
  90. def invalidate(self, key, **kw):
  91. r"""Invalidate a value in the cache.
  92. :param key: the value's key.
  93. :param \**kw: cache configuration arguments. The
  94. backend is configured using these arguments upon first request.
  95. Subsequent requests that use the same series of configuration
  96. values will use that same backend.
  97. """
  98. self.impl.invalidate(key, **self._get_cache_kw(kw, None))
  99. def invalidate_body(self):
  100. """Invalidate the cached content of the "body" method for this
  101. template.
  102. """
  103. self.invalidate("render_body", __M_defname="render_body")
  104. def invalidate_def(self, name):
  105. """Invalidate the cached content of a particular ``<%def>`` within this
  106. template.
  107. """
  108. self.invalidate("render_%s" % name, __M_defname="render_%s" % name)
  109. def invalidate_closure(self, name):
  110. """Invalidate a nested ``<%def>`` within this template.
  111. Caching of nested defs is a blunt tool as there is no
  112. management of scope -- nested defs that use cache tags
  113. need to have names unique of all other nested defs in the
  114. template, else their content will be overwritten by
  115. each other.
  116. """
  117. self.invalidate(name, __M_defname=name)
  118. def _get_cache_kw(self, kw, context):
  119. defname = kw.pop("__M_defname", None)
  120. if not defname:
  121. tmpl_kw = self.template.cache_args.copy()
  122. tmpl_kw.update(kw)
  123. elif defname in self._def_regions:
  124. tmpl_kw = self._def_regions[defname]
  125. else:
  126. tmpl_kw = self.template.cache_args.copy()
  127. tmpl_kw.update(kw)
  128. self._def_regions[defname] = tmpl_kw
  129. if context and self.impl.pass_context:
  130. tmpl_kw = tmpl_kw.copy()
  131. tmpl_kw.setdefault("context", context)
  132. return tmpl_kw
  133. class CacheImpl:
  134. """Provide a cache implementation for use by :class:`.Cache`."""
  135. def __init__(self, cache):
  136. self.cache = cache
  137. pass_context = False
  138. """If ``True``, the :class:`.Context` will be passed to
  139. :meth:`get_or_create <.CacheImpl.get_or_create>` as the name ``'context'``.
  140. """
  141. def get_or_create(self, key, creation_function, **kw):
  142. r"""Retrieve a value from the cache, using the given creation function
  143. to generate a new value.
  144. This function *must* return a value, either from
  145. the cache, or via the given creation function.
  146. If the creation function is called, the newly
  147. created value should be populated into the cache
  148. under the given key before being returned.
  149. :param key: the value's key.
  150. :param creation_function: function that when called generates
  151. a new value.
  152. :param \**kw: cache configuration arguments.
  153. """
  154. raise NotImplementedError()
  155. def set(self, key, value, **kw):
  156. r"""Place a value in the cache.
  157. :param key: the value's key.
  158. :param value: the value.
  159. :param \**kw: cache configuration arguments.
  160. """
  161. raise NotImplementedError()
  162. def get(self, key, **kw):
  163. r"""Retrieve a value from the cache.
  164. :param key: the value's key.
  165. :param \**kw: cache configuration arguments.
  166. """
  167. raise NotImplementedError()
  168. def invalidate(self, key, **kw):
  169. r"""Invalidate a value in the cache.
  170. :param key: the value's key.
  171. :param \**kw: cache configuration arguments.
  172. """
  173. raise NotImplementedError()