Commits

curtis  committed 23b9360 Merge

Merge

  • Participants
  • Parent commits 1a19df0, cf169e5

Comments (0)

Files changed (1)

File gnocchi/tools/cache.py

 
 class _cached_property(object):
     '''Cache the result of a method in the Django cache'''
-    def __init__(self, getter, backend='default', timeout=False,
+    def __init__(self, getter, backend='default', timeout=None,
         use_pickle=False):
         '''Get values from cache'''
         functools.update_wrapper(self, getter)
         key = self._make_key(instance)
         self.cache.delete(key)
 
-def cached_property(func=None, backend='default', timeout=False, use_pickle=False):
+def cached_property(func=None, backend='default', timeout=None, use_pickle=False):
     if func is None:
         return functools.partial(cached_property,
             backend=backend,
         )
     return _cached_property(func, backend=backend, timeout=timeout,
         use_pickle=use_pickle)
+
+class CacheDict(object):
+    '''A wrapper around a Cache to give it a dict feel'''
+    def __init__(self, backend='default', timeout=None, prefix=None, pickle=False):
+        self.pickle = pickle
+        self.timeout = timeout
+        self.prefix = prefix
+        self.cache = get_cache(backend)
+
+    def _key(self, key):
+        if self.prefix:
+            return ':'.join([self.prefix, key])
+        return key
+
+    def get(self, key, default=None):
+        return self.cache.get(self._key(key), default)
+
+    def __getitem__(self, key):
+        _key = self._key(key)
+        if not self.cache.has_key(_key):
+            raise KeyError(key)
+        value = self.cache.get(_key)
+        if self.pickle:
+            value = pickle.dumps(value)
+        return value
+
+    def __setitem__(self, key, value):
+        if self.pickle:
+            value = pickle.dumps(value)
+        self.cache.set(self._key(key), value, timeout=self.timeout)
+
+    def __delitem__(self, key):
+        _key = self._key(key)
+        if not self.cache.has_key(_key):
+            raise AttributeError(key)
+        self.cache.delete(_key)