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, can_preview=False):
12 self.description = description
14 self.markdown = markdown
15 self.can_preview = can_preview
18 class BaseSetting(object):
20 def add_to_class(cls, name):
21 def wrapper(self, *args, **kwargs):
22 return self.value.__getattribute__(name)(*args, **kwargs)
24 setattr(cls, name, wrapper)
26 def __init__(self, name, default, set=None, field_context=None):
28 self.default = default
29 self.field_context = field_context or {}
36 if not set.name in Setting.sets:
37 Setting.sets[set.name] = set
39 Setting.sets[set.name].append(self)
42 return str(self.value)
44 def __unicode__(self):
45 return unicode(self.value)
51 if exp + timedelta(seconds=TMP_MINICACHE_SECONDS) > datetime.now():
54 from forum.models import KeyValue
57 kv = KeyValue.objects.get(key=self.name)
59 self._temp = (v, datetime.now() + timedelta(seconds=TMP_MINICACHE_SECONDS))
61 except KeyValue.DoesNotExist:
62 self._temp = (self.default, datetime.now() + timedelta(seconds=TMP_MINICACHE_SECONDS))
64 logging.error("Error retrieving setting from database (%s): %s" % (self.name, str(e)))
68 def set_value(self, new_value):
69 new_value = self._parse(new_value)
73 def save(self, value):
74 from forum.models import KeyValue
77 kv = KeyValue.objects.get(key=self.name)
78 except KeyValue.DoesNotExist:
79 kv = KeyValue(key=self.name)
81 logging.error("Error savin setting to database (%s): %s" % (self.name, str(e)))
88 self.set_value(self.default)
90 def _parse(self, value):
91 if not isinstance(value, self.base_type):
93 return self.base_type(value)
98 class AnyTypeSetting(BaseSetting):
99 def _parse(self, value):
103 class Setting(object):
107 def __new__(cls, name, default, set=None, field_context=None):
109 return AnyTypeSetting(name, default, set, field_context)
111 deftype = type(default)
113 if deftype in Setting.emulators:
114 emul = Setting.emulators[deftype]
116 emul = type(deftype.__name__ + cls.__name__, (BaseSetting,), {'base_type': deftype})
118 fns = [n for n, f in [(p, getattr(deftype, p)) for p in dir(deftype) if not p in dir(cls)] if callable(f)]
123 Setting.emulators[deftype] = emul
125 return emul(name, default, set, field_context)