Skip to content

Instantly share code, notes, and snippets.

@rtt
Last active January 15, 2022 19:50
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rtt/5029885 to your computer and use it in GitHub Desktop.
Save rtt/5029885 to your computer and use it in GitHub Desktop.
python / jinja2 bytecode cache for Redis
from jinja2 import BytecodeCache
class RedisTemplateBytecodeCache(BytecodeCache):
'''Implements a Jinja2 bytecode cache on top of a pyredis.StrictRedis
connection
See: http://jinja.pocoo.org/docs/2.10/api/#bytecode-cache
'''
def __init__(self, redis_cnx, template_cache_key_prefix=None, ttl=86400):
self.cnx = redis_cnx
self.template_cache_key_prefix = template_cache_key_prefix
self.ttl = ttl
def key(self, k):
if self.template_cache_key_prefix:
return '{}_{}'.format(self.template_cache_key_prefix, k)
return k
def load_bytecode(self, bucket):
bc = self.cnx.get(self.key(bucket.key))
if bc:
bucket.load_bytecode(bc)
def dump_bytecode(self, bucket):
self.cnx.setex(
self.key(bucket.key),
self.ttl,
bucket.bytecode_to_string()
)
def clear(self):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment