django: Caching RSS Feed objects

0 Comments

Django's syndication library works pretty well, it's easy to extend and use, but caching is another story.

Because you don't have access to the view, you can't use fragmented template caching.

Because the Feed class is not a view, we're a bit stuck on that too.

Luckily the class is "callable", meaning we can catch it as it's called.

01.class YourFeed(Feed):
02.  def __call__(self, request, *args, **kwargs):
03.    # Cache the RSS feed
04.    # It has to be done this way because the Feed class is a callable, not a view.
05.    cache_key = self.get_cache_key(*args, **kwargs)
06.    response = cache.get(cache_key)
07. 
08.    if response is None:
09.      response = super(YourFeed, self).__call__(request, *args, **kwargs)
10.      cache.set(cache_key, response, 900) # cache for 15 minutes
11. 
12.    return response
13. 
14.  def get_cache_key(self, *args, **kwargs):
15.    # Override this in subclasses for more caching control
16.    return "%s-%s" % (self.__class__.__module__, '/'.join([ "%s,%s" % (key, val) for key,val in kwargs.items() ]))

This method should work for subclasses of YourFeed also.

tumblr_lhccqjy43R1qgewq6o1_500
Nothing left to do but DANCE!

[ Source ]

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog