-#!/usr/bin/python
+#!/usr/bin/python3
-import logging
-import memcache
+import datetime
+import pickle
+import redis
from . import base
from .decorators import *
-log = logging.getLogger("cache")
-log.propagate = 1
-
-class Client(memcache.Client):
- def debuglog(self, str):
- log.debug(str)
-
-
class Cache(base.Object):
- key_prefix = "pbs_"
-
@lazy_property
- def _cache(self):
- logging.debug("Connecting to memcache...")
-
- return Client(["localhost:11211"], debug=1)
+ def redis(self):
+ """
+ Connects to a local redis server
+ """
+ return redis.Redis(host="localhost", port=6379, db=0)
def get(self, key):
- log.debug("Querying for: %s" % key)
-
- key = "".join((self.key_prefix, key))
-
- return self._cache.get(key)
-
- def set(self, key, val, time=60, min_compress_len=0):
- key = "".join((self.key_prefix, key))
-
- return self._cache.set(key, val, time=time,
- min_compress_len=min_compress_len)
-
- def delete(self, key, time=0):
- key = "".join((self.key_prefix, key))
-
- return self._cache.delete(key, time=time)
+ """
+ Fetches the value of a cached key
+ """
+ value = self.redis.get(key)
+
+ # Nothing found
+ if not value:
+ return
+
+ # Decode pickled value
+ try:
+ return pickle.loads(value)
+
+ # If the value could not be decoded, we return nothing making it look like
+ # no value was found in the cache.
+ except pickle.UnpicklingError:
+ return
+
+ def set(self, key, value, expires=None):
+ """
+ Puts something into the cache
+ """
+ # Figure out when this expires
+ if expires and isinstance(expires, datetime.timedelta):
+ expires = expires.total_seconds()
+
+ # Pickle value
+ value = pickle.dumps(value)
+
+ # Send to redis
+ return self.redis.set(key, value, ex=expires)
+
+ def delete(self, key):
+ """
+ Deletes the key from the cache
+ """
+ return self.redis.delete(key)