1 | from beaker.container import NamespaceManager, Container |
---|
2 | from beaker.exceptions import InvalidCacheBackendError, MissingCacheParameter |
---|
3 | from beaker.synchronization import file_synchronizer, null_synchronizer |
---|
4 | from beaker.util import verify_directory, SyncDict |
---|
5 | |
---|
6 | try: |
---|
7 | import cmemcache as memcache |
---|
8 | except ImportError: |
---|
9 | try: |
---|
10 | import memcache |
---|
11 | except ImportError: |
---|
12 | raise InvalidCacheBackendError("Memcached cache backend requires either the 'memcache' or 'cmemcache' library") |
---|
13 | |
---|
14 | class MemcachedNamespaceManager(NamespaceManager): |
---|
15 | clients = SyncDict() |
---|
16 | |
---|
17 | def __init__(self, namespace, url=None, data_dir=None, lock_dir=None, **params): |
---|
18 | NamespaceManager.__init__(self, namespace) |
---|
19 | |
---|
20 | if not url: |
---|
21 | raise MissingCacheParameter("url is required") |
---|
22 | |
---|
23 | if lock_dir: |
---|
24 | self.lock_dir = lock_dir |
---|
25 | elif data_dir: |
---|
26 | self.lock_dir = data_dir + "/container_mcd_lock" |
---|
27 | if self.lock_dir: |
---|
28 | verify_directory(self.lock_dir) |
---|
29 | |
---|
30 | self.mc = MemcachedNamespaceManager.clients.get(url, |
---|
31 | memcache.Client, url.split(';'), debug=0) |
---|
32 | |
---|
33 | def get_creation_lock(self, key): |
---|
34 | return file_synchronizer( |
---|
35 | identifier="memcachedcontainer/funclock/%s" % self.namespace,lock_dir = self.lock_dir) |
---|
36 | |
---|
37 | def _format_key(self, key): |
---|
38 | return self.namespace + '_' + key.replace(' ', '\302\267') |
---|
39 | |
---|
40 | def __getitem__(self, key): |
---|
41 | return self.mc.get(self._format_key(key)) |
---|
42 | |
---|
43 | def __contains__(self, key): |
---|
44 | value = self.mc.get(self._format_key(key)) |
---|
45 | return value is not None |
---|
46 | |
---|
47 | def has_key(self, key): |
---|
48 | return key in self |
---|
49 | |
---|
50 | def set_value(self, key, value, expiretime=None): |
---|
51 | if expiretime: |
---|
52 | self.mc.set(self._format_key(key), value, time=expiretime) |
---|
53 | else: |
---|
54 | self.mc.set(self._format_key(key), value) |
---|
55 | |
---|
56 | def __setitem__(self, key, value): |
---|
57 | self.set_value(key, value) |
---|
58 | |
---|
59 | def __delitem__(self, key): |
---|
60 | self.mc.delete(self._format_key(key)) |
---|
61 | |
---|
62 | def do_remove(self): |
---|
63 | self.mc.flush_all() |
---|
64 | |
---|
65 | def keys(self): |
---|
66 | raise NotImplementedError("Memcache caching does not support iteration of all cache keys") |
---|
67 | |
---|
68 | class MemcachedContainer(Container): |
---|
69 | namespace_class = MemcachedNamespaceManager |
---|