2012-04-12 85 views
0

我有一个REST-ful服务与Django实现和每个资源访问我想缓存可能被访问的相关数据。预缓存django REST视图

例如在的ressource http://www.example.com/publication/1280将使XML响应:

<publication xmlns="http://www.example.com" xmlns:atom="http://www.w3.org/2005/atom"> 
<abstract>None</abstract> 
<owner> 
    <atom:link rel="owner" type="application/xml" href="http://www.example.com/user/1">ckpuser</atom:link> 
</owner> 
<authors> 
<author> 
    <atom:link rel="author" type="application/xml" href="http://www.example.com/author/564">P. Almquist</atom:link> 
</author> 
</authors> 
<comments></comments> 
<tags></tags> 
<keywords></keywords> 
<referencematerials></referencematerials> 
<peerreviews></peerreviews> 
<fields> 
<howpublished>RFC 1349 (Proposed Standard)</howpublished> 
<url>http://www.ietf.org/rfc/rfc1349.txt</url> 
</fields> 
</publication> 

然后我想预先与ressources http://www.example.com/user/1http://www.example.com/author/564相关的缓存数据。

就像在web服务中给出的响应是一种数据结构,我认为缓存整个响应比queryset更好。如果我们要缓存查询集,那么每当我们访问资源时,我们都会在模板渲染中浪费时间。

这是一个很好的方法吗?我错过了什么吗?

如果这种做法是正确的,那么我怎么会预先缓存使用Django的

'django.middleware.cache.UpdateCacheMiddleware'

'django.middleware.cache.FetchFromCacheMiddleware'提供的中间件的看法?

谢谢

回答

0

尝试Django的per-view cache

基本上,它使用URL(和其他一些东西)作为缓存键,而像这样实现的:

from django.views.decorators.cache import cache_page 

@cache_page(60 * 15) # cache for 15 minutes 
def my_view(request): 
... 

这将缓存视图的XML输出,因为你怀疑需要哪些在高速缓存有效时检索的资源要少于仅高速缓存查询集的资源。

缓存中间件django.middleware.cache.UpdateCacheMiddlewaredjango.middleware.cache.FetchFromCacheMiddleware将缓存整个站点,这很可能不是您想要的。