缓存具有URL参数的django视图 [英] Cache a django view that has URL parameters

查看:113
本文介绍了缓存具有URL参数的django视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近已经实现了Django优秀的缓存框架。但是从我所理解的Django不会缓存在get请求中传递参数的视图。
我有一个Ajax视图,通过获取我想缓存X秒的参数,这将是一个简单的方法?



psuedo代码我目前有一个URL:

  http:// mysites / ajaxthing /?user = foo& items = 10 

只要具有相同的get参数,我想缓存任何这个url。



我目前正在使用缓存装饰器:

  myview(stuff) 

myview = cache_page(myview,60 * 3)

关于 django的不同标题,但它有点过了我的头,我甚至不确定它的正确解决方案

解决方案

对,不同的标题是不正确的解决方案,它是当您要基于客户端请求头(如用户代理等)缓存时使用。



您需要使用低级API 模板片段缓存。这取决于你的意见。



使用低级API,它看起来像这样:

 $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ 
$ = cache.get(user_id_%s%user_id)
如果user为None:
user = User.objects.get(pk = user_id)
cache.set(user_id_%s %user_id,user,10 * 60)#10分钟
...
..


I have recently implemented Django's excellent cache framework. However from what I understand Django will not cache a view that is passed parameters in a get request. I have an Ajax view that is passed get parameters that I would like to cache for X seconds, what would be an easy way to do this?

In psuedo code I currently have a URL:

http://mysites/ajaxthing/?user=foo&items=10

I would like to cache any this url as long as it has the same get parameters.

I'm currently using the cache decorators in my view:

myview(stuff)

myview = cache_page(myview, 60 * 3)

I did read about django's vary headers but it went a little over my head, and I'm not even sure its the correct solution

解决方案

Right, vary headers is not the correct solution, it's used when you want to cache based on client request headers like user-agent etc.

You'll need to use low-level API or template fragment caching. It depends on your views really.

With low-level API it looks something like this:

from django.core.cache import cache

def get_user(request):
    user_id = request.GET.get("user_id")
    user = cache.get("user_id_%s"%user_id)
    if user is None:
        user = User.objects.get(pk=user_id)
        cache.set("user_id_%s"%user_id, user, 10*60) # 10 minutes
    ...
    ..
    .

这篇关于缓存具有URL参数的django视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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