Nasty surprise of Django cache


9th of December 2008

Caching in Django absolutely rocks. Much so because of its simplicity which lowers the threshold to the height of a snowflake. However the simplicity can cause some unexpected surprises.

I ran my site and clicked around until I found a bug I wanted to fix. Then I wrote the test and ran the testrunner but I was getting some really weird behavior. The view looked like this:

 @never_cache
 def club_page(request, clubname):
    club = _find_club(clubname)
    if club is None:
        raise Http404('Could not find the club')

    classes = cache.get('club_page_classes')
    if classes is None:
        classes = ClubClass.objects.filter(club=club).order_by('start_time')
        cache.set('club_page_classes', classes, CACHE_TIMEOUT)
    ...

What happened (and what took me a while to figure out) was that the memcache was still active and being used when running the tests since it's only within the hour that I started running the tests with completely different data. Here's how I solved the problem:

 class ViewsTestCase(unittest.TestCase):
     ...
     def test_club_page(self):
        """ test rendering the club page """
        cache.delete('club_page_classes')
        ...

There must be an easier way to patch the testrunner to reset all cache before running the tests. Anybody?



Comment

Show all 10 comments
 
Name:
Email:
hide my email address.

Your email address will be encoded to prevent email-extraction spiders from reading it so you won't get spammed if you decide to show your email address.