2012-04-12 86 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將緩存整個站點,這很可能不是您想要的。