2006-02-24 14:07:01 +08:00
|
|
|
"Memcached cache backend"
|
|
|
|
|
|
|
|
from django.core.cache.backends.base import BaseCache, InvalidCacheBackendError
|
2007-07-16 17:36:10 +08:00
|
|
|
from django.utils.encoding import smart_unicode, smart_str
|
2006-02-24 14:07:01 +08:00
|
|
|
|
|
|
|
try:
|
2007-03-26 07:29:31 +08:00
|
|
|
import cmemcache as memcache
|
2006-02-24 14:07:01 +08:00
|
|
|
except ImportError:
|
2007-03-26 07:29:31 +08:00
|
|
|
try:
|
|
|
|
import memcache
|
|
|
|
except:
|
|
|
|
raise InvalidCacheBackendError("Memcached cache backend requires either the 'memcache' or 'cmemcache' library")
|
2006-02-24 14:07:01 +08:00
|
|
|
|
|
|
|
class CacheClass(BaseCache):
|
|
|
|
def __init__(self, server, params):
|
|
|
|
BaseCache.__init__(self, params)
|
|
|
|
self._cache = memcache.Client(server.split(';'))
|
|
|
|
|
2007-10-20 23:16:34 +08:00
|
|
|
def add(self, key, value, timeout=0):
|
|
|
|
self._cache.add(key.encode('ascii', 'ignore'), value, timeout or self.default_timeout)
|
|
|
|
|
2006-02-24 14:07:01 +08:00
|
|
|
def get(self, key, default=None):
|
2007-07-16 17:36:10 +08:00
|
|
|
val = self._cache.get(smart_str(key))
|
2006-02-24 14:07:01 +08:00
|
|
|
if val is None:
|
|
|
|
return default
|
|
|
|
else:
|
2007-07-16 17:36:10 +08:00
|
|
|
if isinstance(val, basestring):
|
|
|
|
return smart_unicode(val)
|
|
|
|
else:
|
|
|
|
return val
|
2006-02-24 14:07:01 +08:00
|
|
|
|
|
|
|
def set(self, key, value, timeout=0):
|
2007-07-16 17:36:10 +08:00
|
|
|
if isinstance(value, unicode):
|
|
|
|
value = value.encode('utf-8')
|
|
|
|
self._cache.set(smart_str(key), value, timeout or self.default_timeout)
|
2006-02-24 14:07:01 +08:00
|
|
|
|
|
|
|
def delete(self, key):
|
2007-07-16 17:36:10 +08:00
|
|
|
self._cache.delete(smart_str(key))
|
2006-02-24 14:07:01 +08:00
|
|
|
|
|
|
|
def get_many(self, keys):
|
2007-07-16 17:36:10 +08:00
|
|
|
return self._cache.get_multi(map(smart_str,keys))
|