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, but in order to cache it earlier, it can be tokenized without 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.
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.
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 pickle and base64) for
compatibility with shelve (which requires str keys):
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']