Caching and signals
Adding in cached objects on signals
Was reading this great talk on Django and performance from EuroDjangoCon. There are some good points in there, one I wanted to play with quickly was the caching framework and signals.
I'm a big fan of signals and the idea of setting and deleting the cache as objects change was just something I had to quickly play with. Nothing too revolutionary here, but it simply sets and gets the cache when the object changes.
from django.db import models
from django.core.cache import cache
from django.db.models.signals import post_save, post_delete
def _key(model, id):
return "%s.%s" % (model.__name__, id)
class Car(models.Model):
make = models.CharField(max_length=255)
def key(self):
return _key(self.__class__, self.pk)
def create_cache(sender, **kw):
cache.set(kw["instance"].key(), kw["instance"])
def delete_cache(sender, **kw):
cache.delete(kw["instance"].key())
post_save.connect(create_cache, sender=Car)
post_delete.connect(delete_cache, sender=Car)
So each time the object is created or deleted, the cache gets updated (and thanks to being signals, simple to reuse for any class). And here's a test case.
from django.test import TestCase
from django.core.cache import cache
from models import Car
class CacheTest(TestCase):
def setUp(self):
car = Car()
car.make = "Avensis"
car.save()
self.car = car
self.id = car.pk
def testCar(self):
key = self.car.key()
assert cache.has_key(key)
assert cache.get(key).make == "Avensis"
self.car.make = "Auris"
assert cache.get(key).make == "Avensis"
self.car.save()
assert cache.get(key).make == "Auris"
self.car.delete()
assert not cache.has_key(key)
As an improvement (and indeed the next recipe in my book) it does this through an ObjectManager so that you can just call:
Car.objects.cache(id)
And get the cached object back, setting the object in the cache if it's not already there. There are some problems, including possible race conditions, as slide 30 of the presentation does point out. But it's an interesting start and definitely something I need to play with a bit more.
References
- http://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api
- Django and perfomance talk
Comments
There are no comments.
Login to add comments

