django: Caching RSS Feed objects

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.

class YourFeed(Feed):
def __call__(self, request, *args, **kwargs):
# Cache the RSS feed
# It has to be done this way because the Feed class is a callable, not a view.
cache_key = self.get_cache_key(*args, **kwargs)
response = cache.get(cache_key)

if response is None:
response = super(YourFeed, self).__call__(request, *args, **kwargs)
cache.set(cache_key, response, 900) # cache for 15 minutes

return response

def get_cache_key(self, *args, **kwargs):
# Override this in subclasses for more caching control
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.

Nothing left to do but DANCE!

[ Source ]

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