繁体   English   中英

如何在视图中使用 Django 缓存而不缓存所有页面

[英]How use Django Cache in view without cache all page

我试图使用 Django 缓存来改善我的观点。 效果很好,400 毫秒到 8 毫秒是完美的。 但是当用户第一次访问页面时,Django 缓存页面中的用户信息在标题中,当我尝试注销时,页面继续使用用户信息。

我也尝试在模板中使用缓存,但不好,我的问题来自视图,所以继续 400ms。

我的设置.py

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'unique-snowflake',
    }
}

我的视图.py

@cache_page(60 * 15)
def list(request, tag_slug=None):
    page = request.GET.get('page')
    data = questions_controller.list_questions(request, tag_slug, None, page)
    if data:
        return render(request, 'questions/list.html', data)
    return page_not_found(request, "Page not found")

我在按视图缓存时遇到了同样的问题。 第一个缓存用户的用户信息显示给所有用户。 而且我不能使用模板缓存,因为它很慢。

最好的方法是使用低级缓存 API 缓存视图的最终结果。 如果数据是动态的,则使用django-signals清除陈旧的缓存数据。 根据您的要求调整以下代码。

意见:

from django.core.cache import cache    
def sample(request):
        cached_data = cache.get_many(['query1', 'query2'])
        if cached_data:
            return render(request, 'sample.html', {'query1': cached_data['query1'], 'query2': cached_data['query2']})
        else:
            queryset1 = Model.objects.all()
            queryset2 = Model2.objects.all()
            cache.set_many({'query1': queryset1 , 'query2': queryset2 }, None)
            return render(request, 'sample.html', {'query1': queryset1 , 'query2': queryset2})

型号:

from django.db.models.signals import post_save
from django.core.cache import cache

@receiver(post_save, sender=Model1)
@receiver(post_save, sender=Model2)
def purge_cache(instance, **kwargs):
    cache.delete_many(['query1', 'query2'])

希望这会有所帮助。

每个视图缓存将缓存整个视图,因此它非常适合联系页面之类的内容,但不适合具有动态内容的视图。

听起来模板缓存是您在这里需要的。 对于可以更改的模板部分,您可以向{% cache %}标记添加一个参数以唯一标识它(来自Django 文档):

{% load cache %}
{% cache 500 header request.user.username %}
    .. header for logged in user ..
{% endcache %}

{% cache %}标签中的所有内容现在都将按用户缓存,这样您就不会出现一个用户看到另一个用户的标题的情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM