2 from django.utils.encoding import force_unicode, smart_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 smart_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))
63 self.save(self.default)
65 logging.error("Error retrieving setting from database (%s): %s" % (self.name, str(e)))
69 def set_value(self, new_value):
70 new_value = self._parse(new_value)
74 def save(self, value):
75 from forum.models import KeyValue
78 kv = KeyValue.objects.get(key=self.name)
79 except KeyValue.DoesNotExist:
80 kv = KeyValue(key=self.name)
82 logging.error("Error saving setting to database (%s): %s" % (self.name, str(e)))
89 self.set_value(self.default)
91 def _parse(self, value):
92 if not isinstance(value, self.base_type):
94 return self.base_type(value)
99 class AnyTypeSetting(BaseSetting):
100 def _parse(self, value):
104 class Setting(object):
108 def __new__(cls, name, default, set=None, field_context=None):
110 return AnyTypeSetting(name, default, set, field_context)
112 deftype = type(default)
114 if deftype in Setting.emulators:
115 emul = Setting.emulators[deftype]
117 emul = type(deftype.__name__ + cls.__name__, (BaseSetting,), {'base_type': deftype})
119 fns = [n for n, f in [(p, getattr(deftype, p)) for p in dir(deftype) if not p in dir(cls)] if callable(f)]
124 Setting.emulators[deftype] = emul
126 return emul(name, default, set, field_context)