2 from django.utils.encoding import force_unicode
3 from datetime import datetime, timedelta
5 TMP_MINICACHE_SECONDS = 5
7 class SettingSet(list):
8 def __init__(self, name, title, description, weight=1000, markdown=False):
11 self.description = description
13 self.markdown = markdown
16 class BaseSetting(object):
18 def add_to_class(cls, name):
19 def wrapper(self, *args, **kwargs):
20 return self.value.__getattribute__(name)(*args, **kwargs)
22 setattr(cls, name, wrapper)
24 def __init__(self, name, default, set=None, field_context=None):
26 self.default = default
27 self.field_context = field_context or {}
32 if not set.name in Setting.sets:
33 Setting.sets[set.name] = set
35 Setting.sets[set.name].append(self)
38 return str(self.value)
40 def __unicode__(self):
41 return unicode(self.value)
47 if exp + timedelta(seconds=TMP_MINICACHE_SECONDS) > datetime.now():
50 from forum.models import KeyValue
53 kv = KeyValue.objects.get(key=self.name)
55 self._temp = (v, datetime.now() + timedelta(seconds=TMP_MINICACHE_SECONDS))
60 def set_value(self, new_value):
61 new_value = self._parse(new_value)
64 def save(self, value):
67 from forum.models import KeyValue
70 kv = KeyValue.objects.get(key=self.name)
72 kv = KeyValue(key=self.name)
78 self.set_value(self.default)
80 def _parse(self, value):
81 if not isinstance(value, self.base_type):
83 return self.base_type(value)
88 class AnyTypeSetting(BaseSetting):
89 def _parse(self, value):
93 class Setting(object):
97 def __new__(cls, name, default, set=None, field_context=None):
99 return AnyTypeSetting(name, default, set, field_context)
101 deftype = type(default)
103 if deftype in Setting.emulators:
104 emul = Setting.emulators[deftype]
106 emul = type(deftype.__name__ + cls.__name__, (BaseSetting,), {'base_type': deftype})
108 fns = [n for n, f in [(p, getattr(deftype, p)) for p in dir(deftype) if not p in dir(cls)] if callable(f)]
113 Setting.emulators[deftype] = emul
115 return emul(name, default, set, field_context)