Django - Jinja2缓存模板变量

时间:2016-06-09 13:26:44

标签: django caching

在Jinja2之前我通过memcached使用自定义context_processor进行缓存(对象列表)。

#context_processors.py    
def pikto_studio_caching(request:None, sender:None, **kwargs):
        cache_time = 60*60*24
        cache_key_works = 'pikto_studio:works'

        works = cache.get(cache_key_works)

        if request:
            if not works:
                works = Work.objects.all()
                cache.set(cache_key_works, works, cache_time)
            return {'WORKS':works}
        else:
            cache._cache.flush_all()
            return None

使用jinja2,我无法使用context_processors。我该如何解决这个问题?

感谢。

1 个答案:

答案 0 :(得分:0)

创建jinja2.py文件,将您的缓存函数添加到Jinja2环境全局。

from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse
from django.template import defaultfilters
from jinja2 import Environment


#CACHING
from django.core.cache import cache
from django.db.models.signals import post_save
from apps.web.models import Work, CategoryWork, BasicArticle, CategoryBasicArticle

def caching(request=None, sender=None, **kwargs):
    cache_time = 60*60*24
    cache_key_works = 'pikto_studio:works'

    works = cache.get(cache_key_works)

    if request:
        if not works:
            works = Work.objects.all()
            cache.set(cache_key_works, works, cache_time)
        return {'works':works}
    else:
        cache._cache.flush_all()
        return None



def environment(**options):
    env = Environment(**options)

    env.globals.update({
        'static': staticfiles_storage.url,
        'url': reverse,
        'caching':caching,

    })
    return env

在模板中调用该函数:

{% set works = caching(request)['works'] %}
    {% for work in works %}
     {{ work.title }}
{% endfor %}