Expire cache specific to a django view
Saturday, 8th November, 2008 // 10:27 p.m.It is a well known fact that django has some excellent support for caching. Django's support for caching is amazing.
- Per-Site
- Per-View
- Template Fragment &
- Low level API
Blog like this use per-site caching which cache everything. But there are situations like where user's posts comments on posts. It's frustrating experience for a user when the comment doesn't appear immediately.
On my chat with Will Larson he suggested me a method to reverse engineer the django cache and observe how the key's are created in the cache. If we can find the 'key' in cache it's as easy as write
from django.core.cache import cache cache.delete('key')
After some code follow up on django I was able to find the snippet in /django/utils/cache.py under the method name get_cache_key() which calls generatecache_key to generate cache_key. Here the generatecache_key accepts headerlist on which md5_constructor() is run on each header. Ok that's a bit too much.
The headerlist mainly contains the url. So we need to calculate the md5 of the url (excluding the hostname) which becomes the key in cache. To expire a cache when some one comments on an Post we need insert the cache expiry snippet into the add comment view. In case you are using django comments you might need to write a wrapper function which calls the default django comment view and expire the cache. After writing some code I found a wonderul snippet on djangosnippets by Matt Grayson. This works for me. In your comment view just call
expire_page(path)
where path will be something like /blog/2008/nov/05/making-django-dry-templates-even-drier/. This is generally the get_absolute_url() method. Sometimes you might want to check how this works. Right now you can test in a browser. Results may not be so accurate in a django shell.
Also sometimes you might have a doubt that if a page is generate from cache or by django view. You can use a Firebug to check the headers of the page and check for the Cache-Control max-age=300. If it shows max-age attribute it means it is served from a cache. Other than this there is an excellent view which shows number of keys in the cache, the uptime of the cache and the percentage of hits to the memcache. We can gauge how the memcache is serving. Just plug a url in urls.py and attach it to that view.
Comment Form
2 comments:
001// Will Larson// Monday, 17th November, 2008, 7:48 p.m.
I really like how articles look on your blog. It's just really well put together. Also, thanks for looking into this. I'll need to update Lifeflow to use this snippet after comments are posted.
P.S. I think it should be "Looks like there aren't any comments yet.." instead of "Look's like there are n't any comments yet..".
002// Probiorgohire// Tuesday, 5th January, 2010, 11:42 a.m.
winsome answers i like it