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, that cache can be prepared in advance by simply rendering them with dummy scope. .. code:: python import mstache render('Hello {{.}}', None) Alternatively, performing template tokenization will have the same effect while skipping any 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. The cache key function can be customized via the `cache_make_key` parameter, which can be useful in some situations: - With extremely large templates, hashing will reduce the memory used by keys, useful for both efficiency and cache backend limitations. - With external cache backends with key limitations, serialization will generate compatible keys. As a key hashing example (using xxhash_): .. _xxhash: https://github.com/ifduyue/python-xxhash .. code:: python import pickle import mstache import xxhash def cache_make_key(parameters): return xxhash.xxh3_64_intdigest(pickle.dumps(parameters)) cache = {} print(mstache.render( 'Hello {{.}}', 'world!', cache=cache, cache_make_key=cache_make_key, )) # Hello world! print(list(cache)) # [15733647930184024515] Key serialization example (using :py:mod:`shelve` as cache backend): .. code:: python import pickle import shelve import mstache def cache_make_key(parameters): return pickle.dumps(parameters).hex() with shelve.open('cache.db') as cache: print(mstache.render( 'Hello {{.}}', 'world!', cache=cache, cache_make_key=cache_make_key, )) # Hello world! print(list(cache)) # ['8004951d0000000000000028430b48656c6c6f207b7b2e7d7d9443027b7b9443027d7d948974942e']