1.. _caching_toplevel: 2 3======= 4Caching 5======= 6 7Any template or component can be cached using the ``cache`` 8argument to the ``<%page>``, ``<%def>`` or ``<%block>`` directives: 9 10.. sourcecode:: mako 11 12 <%page cached="True"/> 13 14 template text 15 16The above template, after being executed the first time, will 17store its content within a cache that by default is scoped 18within memory. Subsequent calls to the template's :meth:`~.Template.render` 19method will return content directly from the cache. When the 20:class:`.Template` object itself falls out of scope, its corresponding 21cache is garbage collected along with the template. 22 23The caching system requires that a cache backend be installed; this 24includes either the `Beaker <http://beaker.readthedocs.org/>`_ package 25or the `dogpile.cache <http://dogpilecache.readthedocs.org>`_, as well as 26any other third-party caching libraries that feature Mako integration. 27 28By default, caching will attempt to make use of Beaker. 29To use dogpile.cache, the 30``cache_impl`` argument must be set; see this argument in the 31section :ref:`cache_arguments`. 32 33In addition to being available on the ``<%page>`` tag, the caching flag and all 34its options can be used with the ``<%def>`` tag as well: 35 36.. sourcecode:: mako 37 38 <%def name="mycomp" cached="True" cache_timeout="60"> 39 other text 40 </%def> 41 42... and equivalently with the ``<%block>`` tag, anonymous or named: 43 44.. sourcecode:: mako 45 46 <%block cached="True" cache_timeout="60"> 47 other text 48 </%block> 49 50 51.. _cache_arguments: 52 53Cache Arguments 54=============== 55 56Mako has two cache arguments available on tags that are 57available in all cases. The rest of the arguments 58available are specific to a backend. 59 60The two generic tags arguments are: 61 62* ``cached="True"`` - enable caching for this ``<%page>``, 63 ``<%def>``, or ``<%block>``. 64* ``cache_key`` - the "key" used to uniquely identify this content 65 in the cache. Usually, this key is chosen automatically 66 based on the name of the rendering callable (i.e. ``body`` 67 when used in ``<%page>``, the name of the def when using ``<%def>``, 68 the explicit or internally-generated name when using ``<%block>``). 69 Using the ``cache_key`` parameter, the key can be overridden 70 using a fixed or programmatically generated value. 71 72 For example, here's a page 73 that caches any page which inherits from it, based on the 74 filename of the calling template: 75 76 .. sourcecode:: mako 77 78 <%page cached="True" cache_key="${self.filename}"/> 79 80 ${next.body()} 81 82 ## rest of template 83 84On a :class:`.Template` or :class:`.TemplateLookup`, the 85caching can be configured using these arguments: 86 87* ``cache_enabled`` - Setting this 88 to ``False`` will disable all caching functionality 89 when the template renders. Defaults to ``True``. 90 e.g.: 91 92 .. sourcecode:: python 93 94 lookup = TemplateLookup( 95 directories='/path/to/templates', 96 cache_enabled = False 97 ) 98 99* ``cache_impl`` - The string name of the cache backend 100 to use. This defaults to ``'beaker'``, indicating 101 that the 'beaker' backend will be used. 102 103* ``cache_args`` - A dictionary of cache parameters that 104 will be consumed by the cache backend. See 105 :ref:`beaker_backend` and :ref:`dogpile.cache_backend` for examples. 106 107 108Backend-Specific Cache Arguments 109-------------------------------- 110 111The ``<%page>``, ``<%def>``, and ``<%block>`` tags 112accept any named argument that starts with the prefix ``"cache_"``. 113Those arguments are then packaged up and passed along to the 114underlying caching implementation, minus the ``"cache_"`` prefix. 115 116The actual arguments understood are determined by the backend. 117 118* :ref:`beaker_backend` - Includes arguments understood by 119 Beaker. 120* :ref:`dogpile.cache_backend` - Includes arguments understood by 121 dogpile.cache. 122 123.. _beaker_backend: 124 125Using the Beaker Cache Backend 126------------------------------ 127 128When using Beaker, new implementations will want to make usage 129of **cache regions** so that cache configurations can be maintained 130externally to templates. These configurations live under 131named "regions" that can be referred to within templates themselves. 132 133.. versionadded:: 0.6.0 134 Support for Beaker cache regions. 135 136For example, suppose we would like two regions. One is a "short term" 137region that will store content in a memory-based dictionary, 138expiring after 60 seconds. The other is a Memcached region, 139where values should expire in five minutes. To configure 140our :class:`.TemplateLookup`, first we get a handle to a 141:class:`beaker.cache.CacheManager`: 142 143.. sourcecode:: python 144 145 from beaker.cache import CacheManager 146 147 manager = CacheManager(cache_regions={ 148 'short_term':{ 149 'type': 'memory', 150 'expire': 60 151 }, 152 'long_term':{ 153 'type': 'ext:memcached', 154 'url': '127.0.0.1:11211', 155 'expire': 300 156 } 157 }) 158 159 lookup = TemplateLookup( 160 directories=['/path/to/templates'], 161 module_directory='/path/to/modules', 162 cache_impl='beaker', 163 cache_args={ 164 'manager':manager 165 } 166 ) 167 168Our templates can then opt to cache data in one of either region, 169using the ``cache_region`` argument. Such as using ``short_term`` 170at the ``<%page>`` level: 171 172.. sourcecode:: mako 173 174 <%page cached="True" cache_region="short_term"> 175 176 ## ... 177 178Or, ``long_term`` at the ``<%block>`` level: 179 180.. sourcecode:: mako 181 182 <%block name="header" cached="True" cache_region="long_term"> 183 other text 184 </%block> 185 186The Beaker backend also works without regions. There are a 187variety of arguments that can be passed to the ``cache_args`` 188dictionary, which are also allowable in templates via the 189``<%page>``, ``<%block>``, 190and ``<%def>`` tags specific to those sections. The values 191given override those specified at the :class:`.TemplateLookup` 192or :class:`.Template` level. 193 194With the possible exception 195of ``cache_timeout``, these arguments are probably better off 196staying at the template configuration level. Each argument 197specified as ``cache_XYZ`` in a template tag is specified 198without the ``cache_`` prefix in the ``cache_args`` dictionary: 199 200* ``cache_timeout`` - number of seconds in which to invalidate the 201 cached data. After this timeout, the content is re-generated 202 on the next call. Available as ``timeout`` in the ``cache_args`` 203 dictionary. 204* ``cache_type`` - type of caching. ``'memory'``, ``'file'``, ``'dbm'``, or 205 ``'ext:memcached'`` (note that the string ``memcached`` is 206 also accepted by the dogpile.cache Mako plugin, though not by Beaker itself). 207 Available as ``type`` in the ``cache_args`` dictionary. 208* ``cache_url`` - (only used for ``memcached`` but required) a single 209 IP address or a semi-colon separated list of IP address of 210 memcache servers to use. Available as ``url`` in the ``cache_args`` 211 dictionary. 212* ``cache_dir`` - in the case of the ``'file'`` and ``'dbm'`` cache types, 213 this is the filesystem directory with which to store data 214 files. If this option is not present, the value of 215 ``module_directory`` is used (i.e. the directory where compiled 216 template modules are stored). If neither option is available 217 an exception is thrown. Available as ``dir`` in the 218 ``cache_args`` dictionary. 219 220.. _dogpile.cache_backend: 221 222Using the dogpile.cache Backend 223------------------------------- 224 225`dogpile.cache`_ is a new replacement for Beaker. It provides 226a modernized, slimmed down interface and is generally easier to use 227than Beaker. As of this writing it has not yet been released. dogpile.cache 228includes its own Mako cache plugin -- see :mod:`dogpile.cache.plugins.mako_cache` in the 229dogpile.cache documentation. 230 231Programmatic Cache Access 232========================= 233 234The :class:`.Template`, as well as any template-derived :class:`.Namespace`, has 235an accessor called ``cache`` which returns the :class:`.Cache` object 236for that template. This object is a facade on top of the underlying 237:class:`.CacheImpl` object, and provides some very rudimental 238capabilities, such as the ability to get and put arbitrary 239values: 240 241.. sourcecode:: mako 242 243 <% 244 local.cache.set("somekey", type="memory", "somevalue") 245 %> 246 247Above, the cache associated with the ``local`` namespace is 248accessed and a key is placed within a memory cache. 249 250More commonly, the ``cache`` object is used to invalidate cached 251sections programmatically: 252 253.. sourcecode:: python 254 255 template = lookup.get_template('/sometemplate.html') 256 257 # invalidate the "body" of the template 258 template.cache.invalidate_body() 259 260 # invalidate an individual def 261 template.cache.invalidate_def('somedef') 262 263 # invalidate an arbitrary key 264 template.cache.invalidate('somekey') 265 266You can access any special method or attribute of the :class:`.CacheImpl` 267itself using the :attr:`impl <.Cache.impl>` attribute: 268 269.. sourcecode:: python 270 271 template.cache.impl.do_something_special() 272 273Note that using implementation-specific methods will mean you can't 274swap in a different kind of :class:`.CacheImpl` implementation at a 275later time. 276 277.. _cache_plugins: 278 279Cache Plugins 280============= 281 282The mechanism used by caching can be plugged in 283using a :class:`.CacheImpl` subclass. This class implements 284the rudimental methods Mako needs to implement the caching 285API. Mako includes the :class:`.BeakerCacheImpl` class to 286provide the default implementation. A :class:`.CacheImpl` class 287is acquired by Mako using a ``importlib.metatada`` entrypoint, using 288the name given as the ``cache_impl`` argument to :class:`.Template` 289or :class:`.TemplateLookup`. This entry point can be 290installed via the standard `setuptools`/``setup()`` procedure, underneath 291the `EntryPoint` group named ``"mako.cache"``. It can also be 292installed at runtime via a convenience installer :func:`.register_plugin` 293which accomplishes essentially the same task. 294 295An example plugin that implements a local dictionary cache: 296 297.. sourcecode:: python 298 299 from mako.cache import Cacheimpl, register_plugin 300 301 class SimpleCacheImpl(CacheImpl): 302 def __init__(self, cache): 303 super(SimpleCacheImpl, self).__init__(cache) 304 self._cache = {} 305 306 def get_or_create(self, key, creation_function, **kw): 307 if key in self._cache: 308 return self._cache[key] 309 else: 310 self._cache[key] = value = creation_function() 311 return value 312 313 def set(self, key, value, **kwargs): 314 self._cache[key] = value 315 316 def get(self, key, **kwargs): 317 return self._cache.get(key) 318 319 def invalidate(self, key, **kwargs): 320 self._cache.pop(key, None) 321 322 # optional - register the class locally 323 register_plugin("simple", __name__, "SimpleCacheImpl") 324 325Enabling the above plugin in a template would look like: 326 327.. sourcecode:: python 328 329 t = Template("mytemplate", 330 file="mytemplate.html", 331 cache_impl='simple') 332 333Guidelines for Writing Cache Plugins 334------------------------------------ 335 336* The :class:`.CacheImpl` is created on a per-:class:`.Template` basis. The 337 class should ensure that only data for the parent :class:`.Template` is 338 persisted or returned by the cache methods. The actual :class:`.Template` 339 is available via the ``self.cache.template`` attribute. The ``self.cache.id`` 340 attribute, which is essentially the unique modulename of the template, is 341 a good value to use in order to represent a unique namespace of keys specific 342 to the template. 343* Templates only use the :meth:`.CacheImpl.get_or_create()` method 344 in an implicit fashion. The :meth:`.CacheImpl.set`, 345 :meth:`.CacheImpl.get`, and :meth:`.CacheImpl.invalidate` methods are 346 only used in response to direct programmatic access to the corresponding 347 methods on the :class:`.Cache` object. 348* :class:`.CacheImpl` will be accessed in a multithreaded fashion if the 349 :class:`.Template` itself is used multithreaded. Care should be taken 350 to ensure caching implementations are threadsafe. 351* A library like `Dogpile <http://pypi.python.org/pypi/dogpile.core>`_, which 352 is a minimal locking system derived from Beaker, can be used to help 353 implement the :meth:`.CacheImpl.get_or_create` method in a threadsafe 354 way that can maximize effectiveness across multiple threads as well 355 as processes. :meth:`.CacheImpl.get_or_create` is the 356 key method used by templates. 357* All arguments passed to ``**kw`` come directly from the parameters 358 inside the ``<%def>``, ``<%block>``, or ``<%page>`` tags directly, 359 minus the ``"cache_"`` prefix, as strings, with the exception of 360 the argument ``cache_timeout``, which is passed to the plugin 361 as the name ``timeout`` with the value converted to an integer. 362 Arguments present in ``cache_args`` on :class:`.Template` or 363 :class:`.TemplateLookup` are passed directly, but are superseded 364 by those present in the most specific template tag. 365* The directory where :class:`.Template` places module files can 366 be acquired using the accessor ``self.cache.template.module_directory``. 367 This directory can be a good place to throw cache-related work 368 files, underneath a prefix like ``_my_cache_work`` so that name 369 conflicts with generated modules don't occur. 370 371API Reference 372============= 373 374.. autoclass:: mako.cache.Cache 375 :members: 376 :show-inheritance: 377 378.. autoclass:: mako.cache.CacheImpl 379 :members: 380 :show-inheritance: 381 382.. autofunction:: mako.cache.register_plugin 383 384.. autoclass:: mako.ext.beaker_cache.BeakerCacheImpl 385 :members: 386 :show-inheritance: 387 388