0

I have a REST-ful service implemented with django and for each ressource accessed I would like to cache related data that could be likely accessed.

For instance the ressource http://www.example.com/publication/1280 would give the xml response:

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

Then I would like to pre cache data associated with the ressources http://www.example.com/user/1 and http://www.example.com/author/564.

As in web service the response given is sort of a data structure, I think it's better to cache this entire response than the queryset. If we would cache the queryset, then we would loose time in template rendering each time we access the ressource.

Is it a good approach ? Am I missing something ?

If this approach is right, then how could I pre cache a view using the middleware provided by django

'django.middleware.cache.UpdateCacheMiddleware'

and

'django.middleware.cache.FetchFromCacheMiddleware' ?

Thank you

renard
  • 1,368
  • 6
  • 20
  • 40

1 Answers1

0

Try Django's per-view cache.

Basically, it uses the URL (and some other things) as the cache key, and is implemented like this:

from django.views.decorators.cache import cache_page

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

This will cache the XML output of the view, which as you suspect will require less resources to retrieve while the cache is valid than only caching the queryset.

The cache middlewares django.middleware.cache.UpdateCacheMiddleware and django.middleware.cache.FetchFromCacheMiddleware will cache the entire site, which is most likely not what you want.

Chris Lawlor
  • 47,306
  • 11
  • 48
  • 68