Template cache -------------- **mstache** implements a default cache storing the 1024 last used template tokenizations to skip that slower parsing step for the common templates, exposed as :py:attr:`mstache.default_cache`. The cache backend can be customized via `cache` parameter, accepting any :py:class:`collections.abc.MutableMapping` instance. Pre-caching =========== As templates are parsed and cached on their first render, but in order to cache it earlier, it can be tokenized without rendering: .. code:: python import mstache template = 'Hello {{.}}' mstache.tokenize(template.encode()) Disabling cache =============== Disabling **mstache** template cache, which can be specially useful for one-off templates, can be achieved by providing your own cache mapping. For example, by passing an empty disposable :py:class:`dict`, the compiled template will be discarded during garbage collection. .. code:: python import mstache print(mstache.render( 'Hello {{.}}', 'world!', cache={}, )) # Hello world! Key customization ================= The default template key function, :py:func:`mstache.default_cache_make_key`, uses the tuple of the few relevant parameters passed to :py:func:`mstache.tokenize`, including the full template data. Said cache key function can be replaced via `cache_make_key` parameter, which can be useful in some situations: - With large templates, hashing can reduce the memory used by keys, useful for both efficiency and cache backend limitations. - With external cache backends with key limitations, bespoke serialization can generate compatible keys. Key hashing ~~~~~~~~~~~ Key hashing example (using xxhash_) to either reduce cache key memory footprint or improve compatibility with cache backends. .. _xxhash: https://github.com/ifduyue/python-xxhash .. code:: python import pickle import xxhash import mstache cache = {} print(mstache.render( 'Hello {{.}}', 'world!', cache=cache, cache_make_key=lambda x: ( xxhash.xxh3_64_intdigest(pickle.dumps(x)) ), )) # Hello world! print(list(cache)) # [15733647930184024515] Key serialization ~~~~~~~~~~~~~~~~~ Key serialization example (using :py:mod:`pickle` and :py:mod:`base64`) for compatibility with :py:mod:`shelve` (which requires :class:`str` keys): .. code:: python import base64 import pickle import shelve import mstache with shelve.open('cache.db') as cache: print(mstache.render( 'Hello {{.}}', 'world!', cache=cache, cache_make_key=lambda x: ( base64.b64encode(pickle.dumps(x)).decode() ), )) # Hello world! print(list(cache)) # ['gASVHwAAAAAAAAAoQwtIZWxsbyB7ey59fZRDAnt7lEMCfX2UiYmJdJQu']