|
0
|
1 |
"Memcached cache backend" |
|
|
2 |
|
|
|
3 |
from django.core.cache.backends.base import BaseCache, InvalidCacheBackendError |
|
|
4 |
from django.utils.encoding import smart_unicode, smart_str |
|
|
5 |
|
|
|
6 |
try: |
|
|
7 |
import cmemcache as memcache |
|
|
8 |
except ImportError: |
|
|
9 |
try: |
|
|
10 |
import memcache |
|
|
11 |
except: |
|
|
12 |
raise InvalidCacheBackendError("Memcached cache backend requires either the 'memcache' or 'cmemcache' library") |
|
|
13 |
|
|
|
14 |
class CacheClass(BaseCache): |
|
|
15 |
def __init__(self, server, params): |
|
|
16 |
BaseCache.__init__(self, params) |
|
|
17 |
self._cache = memcache.Client(server.split(';')) |
|
|
18 |
|
|
|
19 |
def add(self, key, value, timeout=0): |
|
|
20 |
if isinstance(value, unicode): |
|
|
21 |
value = value.encode('utf-8') |
|
|
22 |
return self._cache.add(smart_str(key), value, timeout or self.default_timeout) |
|
|
23 |
|
|
|
24 |
def get(self, key, default=None): |
|
|
25 |
val = self._cache.get(smart_str(key)) |
|
|
26 |
if val is None: |
|
|
27 |
return default |
|
|
28 |
else: |
|
|
29 |
if isinstance(val, basestring): |
|
|
30 |
return smart_unicode(val) |
|
|
31 |
else: |
|
|
32 |
return val |
|
|
33 |
|
|
|
34 |
def set(self, key, value, timeout=0): |
|
|
35 |
if isinstance(value, unicode): |
|
|
36 |
value = value.encode('utf-8') |
|
|
37 |
self._cache.set(smart_str(key), value, timeout or self.default_timeout) |
|
|
38 |
|
|
|
39 |
def delete(self, key): |
|
|
40 |
self._cache.delete(smart_str(key)) |
|
|
41 |
|
|
|
42 |
def get_many(self, keys): |
|
|
43 |
return self._cache.get_multi(map(smart_str,keys)) |
|
|
44 |
|
|
|
45 |
def close(self, **kwargs): |
|
|
46 |
self._cache.disconnect_all() |
|
|
47 |
|
|
|
48 |
def incr(self, key, delta=1): |
|
|
49 |
return self._cache.incr(key, delta) |
|
|
50 |
|
|
|
51 |
def decr(self, key, delta=1): |
|
|
52 |
return self._cache.decr(key, delta) |