Last active
June 29, 2017 22:01
-
-
Save jpassaro/6b0942c2affc63084b3328466ca3e2a4 to your computer and use it in GitHub Desktop.
Example: using werkzeug cache with flask.render_template_string
This file contains hidden or 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
>>> # flask shell | |
>>> from short_templates import * | |
>>> NameTemplate.render(site_name='Flask', name='John') | |
u'Thank you for visiting Flask. I am John.' | |
>>> NameDateTemplate.render(site_name='Flask', name='John') | |
u'Thank you for visiting Flask. I am John. Today is 2017-06-29.' |
This file contains hidden or 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
# app/short_templates.py | |
import json | |
from datetime import date | |
from flask import render_template_string | |
from werkzeug.contrib.cache import SimpleCache # or Redis or Memcache | |
cache = SimpleCache() | |
class CachedTemplateString(object): | |
"""Subclass me and make the template my docstring. I will cache the results.""" | |
_cache = cache | |
@classmethod | |
def render(cls, **kwargs): | |
params = cls.defaults() | |
params.update(kwargs) | |
key = cls.make_key(**params) | |
val = cls._cache.get(key) | |
if val is None: | |
val = render_template_string(cls.__doc__, **params) | |
cls._cache.set(key, val) | |
return val | |
@classmethod | |
def make_key(cls, **kwargs): | |
return json.dumps((cls.__name__, kwargs)) | |
@classmethod | |
def defaults(cls): | |
return {} | |
class NameTemplate(CachedTemplateString): | |
"""Thank you for visiting {{site_name}}. I am {{name}}.""" | |
class NameDateTemplate(CachedTemplateString): | |
__doc__ = NameTemplate.__doc__ + " Today is {{today}}." | |
@classmethod | |
def defaults(cls): | |
return {'today': date.today()} | |
@classmethod | |
def make_key(cls, today=None, **kwargs): | |
return super(NameDateTemplate, cls).make_key(today=str(today), | |
**kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment