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 mstache.default_cache.

The cache backend can be customized via cache parameter, accepting any 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.

import mstache

render('Hello {{.}}', None)

Alternatively, performing template tokenization will have the same effect while skipping any rendering.

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 dict, the compiled template will be discarded during garbage collection.

import mstache

print(mstache.render(
    'Hello {{.}}',
    'world!',
    cache={},
    ))
# Hello world!

Key customization

The default template key function, mstache.default_cache_make_key(), uses the tuple of the few relevant parameters passed to 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):

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 shelve as cache backend):

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']