Debian Codegraph @

src/flask_caching/backends/memcache.py

raw
1 """
2 flask_caching.backends.memcache
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 The memcache caching backend.
6
7 :copyright: (c) 2018 by Peter Justin.
8 :copyright: (c) 2010 by Thadeus Burgess.
9 :license: BSD, see LICENSE for more details.
10 """
11
12 import pickle
13 import re
14
15 from cachelib import MemcachedCache as CachelibMemcachedCache
16
17 from flask_caching.backends.base import BaseCache
18
19 _test_memcached_key = re.compile(r"[^\x00-\x21\xff]{1,250}$").match
20
21
22 class MemcachedCache(BaseCache, CachelibMemcachedCache):
23 """A cache that uses memcached as backend.
24
25 The first argument can either be an object that resembles the API of a
26 :class:`memcache.Client` or a tuple/list of server addresses. In the
27 event that a tuple/list is passed, Werkzeug tries to import the best
28 available memcache library.
29
30 This cache looks into the following packages/modules to find bindings for
31 memcached:
32
33 - ``pylibmc``
34 - ``google.appengine.api.memcached``
35 - ``memcached``
36 - ``libmc``
37
38 Implementation notes: This cache backend works around some limitations in
39 memcached to simplify the interface. For example unicode keys are encoded
40 to utf-8 on the fly. Methods such as :meth:`~BaseCache.get_dict` return
41 the keys in the same format as passed. Furthermore all get methods
42 silently ignore key errors to not cause problems when untrusted user data
43 is passed to the get methods which is often the case in web applications.
44
45 :param servers: a list or tuple of server addresses or alternatively
46 a :class:`memcache.Client` or a compatible client.
47 :param default_timeout: the default timeout that is used if no timeout is
48 specified on :meth:`~BaseCache.set`. A timeout of
49 0 indicates that the cache never expires.
50 :param key_prefix: a prefix that is added before all keys. This makes it
51 possible to use the same memcached server for different
52 applications. Keep in mind that
53 :meth:`~BaseCache.clear` will also clear keys with a
54 different prefix.
55 """
56
57 def __init__(self, servers=None, default_timeout=300, key_prefix=None):
58 BaseCache.__init__(self, default_timeout=default_timeout)
59 CachelibMemcachedCache.__init__(
60 self,
61 servers=servers,
62 default_timeout=default_timeout,
63 key_prefix=key_prefix,
64 )
65
66 @classmethod
67 def factory(cls, app, config, args, kwargs):
68 args.append(config["CACHE_MEMCACHED_SERVERS"])
69 kwargs.update(dict(key_prefix=config["CACHE_KEY_PREFIX"]))
70 return cls(*args, **kwargs)
71
72 def delete_many(self, *keys):
73 new_keys = []
74 for key in keys:
75 key = self._normalize_key(key)
76 if _test_memcached_key(key):
77 new_keys.append(key)
78 return self._client.delete_multi(new_keys)
79
80 def inc(self, key, delta=1):
81 key = self._normalize_key(key)
82 return self._client.incr(key, delta)
83
84 def dec(self, key, delta=1):
85 key = self._normalize_key(key)
86 return self._client.decr(key, delta)
87
88
89 class SASLMemcachedCache(MemcachedCache):
90 def __init__(
91 self,
92 servers=None,
93 default_timeout=300,
94 key_prefix=None,
95 username=None,
96 password=None,
97 **kwargs,
98 ):
99 super().__init__(default_timeout=default_timeout)
100
101 if servers is None:
102 servers = ["127.0.0.1:11211"]
103
104 import pylibmc
105
106 self._client = pylibmc.Client(
107 servers, username=username, password=password, binary=True, **kwargs
108 )
109
110 self.key_prefix = key_prefix
111
112 @classmethod
113 def factory(cls, app, config, args, kwargs):
114 args.append(config["CACHE_MEMCACHED_SERVERS"])
115 kwargs.update(
116 dict(
117 username=config["CACHE_MEMCACHED_USERNAME"],
118 password=config["CACHE_MEMCACHED_PASSWORD"],
119 key_prefix=config["CACHE_KEY_PREFIX"],
120 )
121 )
122 return cls(*args, **kwargs)
123
124
125 class SpreadSASLMemcachedCache(SASLMemcachedCache):
126 """Simple Subclass of SASLMemcached client that will spread the value
127 across multiple keys if they are bigger than a given threshold.
128
129 Spreading requires using pickle to store the value, which can significantly
130 impact the performance.
131 """
132
133 def __init__(self, *args, **kwargs):
134 """
135 Kwargs:
136 chunksize (int): max length of a pickled object that can fit in
137 memcached (memcache has an upper limit of 1MB for values,
138 default: 1048448)
139 """
140 self.chunksize = kwargs.get("chunksize", 1048448)
141 self.maxchunk = kwargs.get("maxchunk", 32)
142 super().__init__(*args, **kwargs)
143
144 @classmethod
145 def factory(cls, app, config, args, kwargs):
146 args.append(config["CACHE_MEMCACHED_SERVERS"])
147 kwargs.update(
148 dict(
149 username=config.get("CACHE_MEMCACHED_USERNAME"),
150 password=config.get("CACHE_MEMCACHED_PASSWORD"),
151 key_prefix=config.get("CACHE_KEY_PREFIX"),
152 )
153 )
154
155 return cls(*args, **kwargs)
156
157 def delete(self, key):
158 for skey in self._genkeys(key):
159 super().delete(skey)
160
161 def set(self, key, value, timeout=None, chunk=True):
162 """Set a value in cache, potentially spreading it across multiple key.
163
164 :param key: The cache key.
165 :param value: The value to cache.
166 :param timeout: The timeout after which the cache will be invalidated.
167 :param chunk: If set to `False`, then spreading across multiple keys
168 is disabled. This can be faster, but it will fail if
169 the value is bigger than the chunks. It requires you
170 to get back the object by specifying that it is not
171 spread.
172 """
173 if chunk:
174 return self._set(key, value, timeout=timeout)
175 else:
176 return super().set(key, value, timeout=timeout)
177
178 def _set(self, key, value, timeout=None):
179 # pickling/unpickling add an overhead,
180 # I didn't found a good way to avoid pickling/unpickling if
181 # key is smaller than chunksize, because in case or <werkzeug.requests>
182 # getting the length consume the data iterator.
183 serialized = pickle.dumps(value, 2)
184 values = {}
185 len_ser = len(serialized)
186 chks = range(0, len_ser, self.chunksize)
187
188 if len(chks) > self.maxchunk:
189 raise ValueError(f"Cannot store value in less than {self.maxchunk} keys")
190
191 for i in chks:
192 values[f"{key}.{i // self.chunksize}"] = serialized[i : i + self.chunksize]
193
194 super().set_many(values, timeout)
195
196 def get(self, key, chunk=True):
197 """Get a cached value.
198
199 :param chunk: If set to ``False``, it will return a cached value
200 that is spread across multiple keys.
201 """
202 if chunk:
203 return self._get(key)
204 else:
205 return super().get(key)
206
207 def _genkeys(self, key):
208 return [f"{key}.{i}" for i in range(self.maxchunk)]
209
210 def _get(self, key):
211 to_get = [f"{key}.{i}" for i in range(self.maxchunk)]
212 result = super().get_many(*to_get)
213 serialized = b"".join(v for v in result if v is not None)
214
215 if not serialized:
216 return None
217
218 return pickle.loads(serialized)