2 from django.utils.encoding import force_unicode
3 from datetime import datetime, timedelta
6 TMP_MINICACHE_SECONDS = 5
8 class SettingSet(list):
9 def __init__(self, name, title, description, weight=1000, markdown=False):
12 self.description = description
14 self.markdown = markdown
17 class BaseSetting(object):
19 def add_to_class(cls, name):
20 def wrapper(self, *args, **kwargs):
21 return self.value.__getattribute__(name)(*args, **kwargs)
23 setattr(cls, name, wrapper)
25 def __init__(self, name, default, set=None, field_context=None):
27 self.default = default
28 self.field_context = field_context or {}
33 if not set.name in Setting.sets:
34 Setting.sets[set.name] = set
36 Setting.sets[set.name].append(self)
39 return str(self.value)
41 def __unicode__(self):
42 return unicode(self.value)
48 if exp + timedelta(seconds=TMP_MINICACHE_SECONDS) > datetime.now():
51 from forum.models import KeyValue
54 kv = KeyValue.objects.get(key=self.name)
56 self._temp = (v, datetime.now() + timedelta(seconds=TMP_MINICACHE_SECONDS))
58 except KeyValue.DoesNotExist:
59 self._temp = (self.default, datetime.now() + timedelta(seconds=TMP_MINICACHE_SECONDS))
61 logging.error("Error retrieving setting from database (%s): %s" % (self.name, str(e)))
65 def set_value(self, new_value):
66 new_value = self._parse(new_value)
70 def save(self, value):
71 from forum.models import KeyValue
74 kv = KeyValue.objects.get(key=self.name)
75 except KeyValue.DoesNotExist:
76 kv = KeyValue(key=self.name)
78 logging.error("Error savin setting to database (%s): %s" % (self.name, str(e)))
85 self.set_value(self.default)
87 def _parse(self, value):
88 if not isinstance(value, self.base_type):
90 return self.base_type(value)
95 class AnyTypeSetting(BaseSetting):
96 def _parse(self, value):
100 class Setting(object):
104 def __new__(cls, name, default, set=None, field_context=None):
106 return AnyTypeSetting(name, default, set, field_context)
108 deftype = type(default)
110 if deftype in Setting.emulators:
111 emul = Setting.emulators[deftype]
113 emul = type(deftype.__name__ + cls.__name__, (BaseSetting,), {'base_type': deftype})
115 fns = [n for n, f in [(p, getattr(deftype, p)) for p in dir(deftype) if not p in dir(cls)] if callable(f)]
120 Setting.emulators[deftype] = emul
122 return emul(name, default, set, field_context)