1 from django.db import models
2 from django.core.cache import cache
3 from django.conf import settings
5 # import cPickle as pickle
10 class PickledObject(str):
13 class PickledObjectField(models.Field):
14 __metaclass__ = models.SubfieldBase
16 def to_python(self, value):
17 if isinstance (value, PickledObject):
21 return pickle.loads(value.encode('utf-8'))
25 def get_db_prep_save(self, value):
27 if isinstance(value, PickledObject):
30 value = pickle.dumps(value)
34 def get_internal_type(self):
38 class KeyValueManager(models.Manager):
40 def create_cache_key(self, key):
41 return "%s:key_value:%s" % (settings.APP_URL, key)
43 def save_to_cache(self, instance):
44 cache.set(self.create_cache_key(instance.key), instance, 2592000)
46 def remove_from_cache(self, instance):
47 cache.delete(self.create_cache_key(instance.key))
49 def get(self, **kwargs):
51 instance = cache.get(self.create_cache_key(kwargs['key']))
54 instance = super(KeyValueManager, self).get(**kwargs)
55 self.save_to_cache(instance)
60 return super(KeyValueManager, self).get(**kwargs)
62 class KeyValue(models.Model):
63 key = models.CharField(max_length=255, unique=True)
64 value = PickledObjectField()
66 objects = KeyValueManager()
71 def save(self, *args, **kwargs):
72 super(KeyValue, self).save(*args, **kwargs)
73 KeyValue.objects.save_to_cache(self)
76 KeyValue.objects.remove_from_cache(self)
77 super(KeyValue, self).delete()