]> git.openstreetmap.org Git - osqa.git/blob - osqa/forum/models/utils.py
Updated CSS and reformatted in IntelliJ
[osqa.git] / osqa / forum / models / utils.py
1 from django.db import models
2 from django.core.cache import cache
3 from django.conf import settings
4 #try:
5 #       import cPickle as pickle
6 #except ImportError:
7 import pickle
8 import django.dispatch
9
10 class PickledObject(str):
11         pass
12
13 class PickledObjectField(models.Field):
14     __metaclass__ = models.SubfieldBase
15
16     def to_python(self, value):
17         if isinstance (value, PickledObject):
18             return value
19
20         try:
21             return pickle.loads(value.encode('utf-8'))
22         except:
23             return value
24     
25     def get_db_prep_save(self, value):
26         if value is not None:
27             if isinstance(value, PickledObject):
28                 return str(value)
29             else:
30                             value = pickle.dumps(value)
31
32         return value
33
34     def get_internal_type(self):
35         return 'TextField'
36
37
38 class KeyValueManager(models.Manager):
39
40     def create_cache_key(self, key):
41         return "%s:key_value:%s" % (settings.APP_URL, key)
42
43     def save_to_cache(self, instance):
44         cache.set(self.create_cache_key(instance.key), instance, 2592000)
45
46     def remove_from_cache(self, instance):
47         cache.delete(self.create_cache_key(instance.key))
48
49     def get(self, **kwargs):
50         if 'key' in kwargs:
51             instance = cache.get(self.create_cache_key(kwargs['key']))
52
53             if instance is None:
54                 instance = super(KeyValueManager, self).get(**kwargs)
55                 self.save_to_cache(instance)
56
57             return instance
58
59         else:
60             return super(KeyValueManager, self).get(**kwargs)
61
62 class KeyValue(models.Model):
63     key = models.CharField(max_length=255, unique=True)
64     value = PickledObjectField()
65
66     objects = KeyValueManager()
67
68     class Meta:
69         app_label = 'forum'
70
71     def save(self, *args, **kwargs):
72         super(KeyValue, self).save(*args, **kwargs)
73         KeyValue.objects.save_to_cache(self)
74
75     def delete(self):
76         KeyValue.objects.remove_from_cache(self)
77         super(KeyValue, self).delete()