Skip to content

Commit

Permalink
Add template cache support
Browse files Browse the repository at this point in the history
  • Loading branch information
DangerOnTheRanger committed Apr 24, 2019
1 parent e4e5622 commit 374e1ed
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
25 changes: 25 additions & 0 deletions jinja_cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import cache

import jinja2


class KeystoreCache(jinja2.BytecodeCache):
def __init__(self):
super().__init__()
self._cache_connection = None
def load_bytecode(self, bucket):
cache_key = self._template_key(bucket.key)
self._ensure_connection()
cached_bytecode = self._cache_connection.get(cache_key)
if cached_bytecode:
bucket.bytecode_from_string(bytes(cached_bytecode, "utf-8"))
def dump_bytecode(self, bucket):
cache_key = self._template_key(bucket.key)
bytecode = str(bucket.bytecode_to_string())
self._ensure_connection()
self._cache_connection.set(cache_key, bytecode)
def _ensure_connection(self):
if not self._cache_connection:
self._cache_connection = cache.Cache()
def _template_key(self, template_name):
return "jinja2-template-%s" % template_name
11 changes: 10 additions & 1 deletion shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,17 @@
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from flask_restful import Api
from werkzeug.datastructures import ImmutableDict

app = Flask(__name__, static_url_path='')
import jinja_cache


class ManiwaniApp(Flask):
jinja_options = ImmutableDict(extensions=["jinja2.ext.autoescape", "jinja2.ext.with_"],
bytecode_cache=jinja_cache.KeystoreCache())


app = ManiwaniApp(__name__, static_url_path='')
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
Expand Down

0 comments on commit 374e1ed

Please sign in to comment.