Last active
January 15, 2022 19:50
-
-
Save rtt/5029885 to your computer and use it in GitHub Desktop.
python / jinja2 bytecode cache for Redis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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