如何在视图中使用Django缓存而不缓存所有页面 [英] How use Django Cache in view without cache all page

查看:211
本文介绍了如何在视图中使用Django缓存而不缓存所有页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Django Cache改善我的观点。效果很好,400ms至8ms是完美的。但是,当用户首次访问页面时,Django缓存页面的标题中包含用户信息,当我尝试注销时,页面将继续显示用户信息。

I trying to use Django Cache to make better my views. Works great, 400ms to 8ms is perfect. But when user access page for the first time, Django cache page with user info in header and when I try log out, page continue with user info.

我也尝试在模板中使用缓存,但是效果不好,我的问题来自视图,因此请继续执行400ms。

I try use cache in template too, but isn't good, my problem come from view, so continue 400ms.

我的 settings.py

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

我的 view.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")


推荐答案

我遇到了相同的问题 per-view 缓存出现问题。显示所有用户的第一个缓存用户的用户信息。而且我不能使用模板缓存作为

I faced the same problem with per-view caching. User info of the first cached user shows for all users. And I can't use Template caching as it is slow.

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

Best approach is to cache the final result of the view using low-level cache API. If the data is dynamic then use django-signals to clear the stale cached data. Tweak the below code to your requirement.

视图:

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'])

希望这会有所帮助。

这篇关于如何在视图中使用Django缓存而不缓存所有页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆