Register
Login

Django Caching
29.4.2009

The site just got mildly reddited, so I've decided to implement some caching in order to deal with possibly higher loads in the future (when I unveil a large-scale autonomous project that I've been working on). On my ongoing quest of Django awesomness, I have recently stumbled upon generic views, which somewhat clouded the idea of caching.

First, the Django docs provide an example that lists something like (r'^foo/(\d{1,2})/$', cache_page(my_view, 60 * 15)), to be put in urls.py in order to cache a view. However, this is quite contradictory to their other references of containing the view reference in a string (as shown in the tutorial) in the urls file. This is not a big deal, but the error message doesn't refer to the actual location of the problem well and makes debugging a tad more difficult. What they should have made clear, was that you can just import the view definition, and insert the variable directly rather than passing in its title as a string.

The second issue I ran into was how to separate the anonymous caches and individual ones. I still have not been able to come up with a simple solution using generic views, but have created some makeshift code that roughly accomplishes what I wanted (feel free to suggest a better one!). Although I don't believe that I'm using the cache middleware, I found a reference to the 'CACHE_MIDDLEWARE_ANONYMOUS_ONLY' option in settings.py and decided to give it a shot. Viola! The site now seems to only do caching when necessary for anonymous users. Assuming that I don't get a massive number of users registering in the near future, everything should work quite nicely.

Using memcached as a backend with per-view caching, I am seeing a 10X speedup on the more complex pages. Quite an improvement for the public views!

comments:
Post

Type the string below:

  ____ ____ _   _ _   
/ ___/ ___| | | | |_
| | | | _| | | | __|
| |__| |_| | |_| | |_
\____\____|\___/ \__|

*Comments may take up to 60 seconds to appear.