简体   繁体   English

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

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

I trying to use Django Cache to make better my views.我试图使用 Django 缓存来改善我的观点。 Works great, 400ms to 8ms is perfect.效果很好,400 毫秒到 8 毫秒是完美的。 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.但是当用户第一次访问页面时,Django 缓存页面中的用户信息在标题中,当我尝试注销时,页面继续使用用户信息。

I try use cache in template too, but isn't good, my problem come from view, so continue 400ms.我也尝试在模板中使用缓存,但不好,我的问题来自视图,所以继续 400ms。

My settings.py我的设置.py

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

My view.py我的视图.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")

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.而且我不能使用模板缓存,因为它很慢。

Best approach is to cache the final result of the view using low-level cache API .最好的方法是使用低级缓存 API 缓存视图的最终结果。 If the data is dynamic then use django-signals to clear the stale cached data.如果数据是动态的,则使用django-signals清除陈旧的缓存数据。 Tweak the below code to your requirement.根据您的要求调整以下代码。

Views:意见:

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})

Models:型号:

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

Hope this helps.希望这会有所帮助。

Per-view caching will cache the entire view, so it's a good fit for something like a contact page, but it isn't a good fit for views that have dynamic content.每个视图缓存将缓存整个视图,因此它非常适合联系页面之类的内容,但不适合具有动态内容的视图。

It sounds like template caching is what you'll need here.听起来模板缓存是您在这里需要的。 For parts of the template that can change, you can add an argument to the {% cache %} tag to uniquely identify it (from the Django docs ):对于可以更改的模板部分,您可以向{% cache %}标记添加一个参数以唯一标识它(来自Django 文档):

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

Everything in the {% cache %} tag will now be cached per-user so you don't end up with a situation where one user is seeing another user's header. {% cache %}标签中的所有内容现在都将按用户缓存,这样您就不会出现一个用户看到另一个用户的标题的情况。

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

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