| 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 |
from functools import partial |
| 15 |
from typing import Any |
| 16 |
|
| 17 |
from cachelib import MemcachedCache as CachelibMemcachedCache |
| 18 |
from flask import Flask |
| 19 |
|
| 20 |
from flask_caching.backends.base import BaseCache |
| 21 |
from flask_caching.utils import _Timeout |
| 22 |
|
| 23 |
_test_memcached_key = re.compile(r"[^\x00-\x21\xff]{1,250}$").match |
| 24 |
|
| 25 |
|
| 26 |
class MemcachedCache(BaseCache, CachelibMemcachedCache): |
| 27 |
"""A cache that uses memcached as backend. |
| 28 |
|
| 29 |
The first argument can either be an object that resembles the API of a |
| 30 |
``memcache.Client`` or a tuple/list of server addresses. In the |
| 31 |
event that a tuple/list is passed, CacheLib tries to import the best |
| 32 |
available memcache library. |
| 33 |
|
| 34 |
This cache looks into the following packages/modules to find bindings for |
| 35 |
memcached: |
| 36 |
|
| 37 |
- ``pylibmc`` |
| 38 |
- ``google.appengine.api.memcached`` |
| 39 |
- ``memcached`` |
| 40 |
- ``libmc`` |
| 41 |
|
| 42 |
Implementation notes: |
| 43 |
This cache backend works around some limitations in memcached to |
| 44 |
simplify the interface. For example unicode keys are encoded to |
| 45 |
UTF-8 on the fly. Methods such as :meth:`~.BaseCache.get_dict` return |
| 46 |
the keys in the same format as passed. Furthermore all get methods |
| 47 |
silently ignore key errors to not cause problems when untrusted user data |
| 48 |
is passed to the get methods which is often the case in web applications. |
| 49 |
This cache doesn't have a serializer since the underlying memcached client |
| 50 |
libraries handle serialization internally." |
| 51 |
|
| 52 |
:param servers: a list or tuple of server addresses or alternatively |
| 53 |
a ``memcache.Client`` or a compatible client. |
| 54 |
:param default_timeout: the default timeout that is used if no timeout is |
| 55 |
specified on :meth:`~BaseCache.set`. A timeout of |
| 56 |
0 indicates that the cache never expires. |
| 57 |
:param key_prefix: a prefix that is added before all keys. This makes it |
| 58 |
possible to use the same memcached server for different |
| 59 |
applications. Keep in mind that |
| 60 |
:meth:`~.BaseCache.clear` will also clear keys with a |
| 61 |
different prefix. |
| 62 |
:param pool_size: the size of the connection pool. This is only used if |
| 63 |
the memcached client library supports connection pooling. |
| 64 |
|
| 65 |
.. versionadded:: 2.5.0 |
| 66 |
:param pool_blocking: if the connection pool is exhausted, should the |
| 67 |
client block until a connection is available or raise |
| 68 |
an exception. This is only used if the memcached |
| 69 |
client library supports connection pooling. |
| 70 |
|
| 71 |
.. versionadded:: 2.5.0 |
| 72 |
:param ignore_delete_many_errors: If set to ``False`` the ``delete_many`` |
| 73 |
method raises a ``RuntimeError`` in case |
| 74 |
a key couldn't be deleted. |
| 75 |
Defaults to ``False``. |
| 76 |
|
| 77 |
.. versionadded:: 2.5.0 |
| 78 |
""" |
| 79 |
|
| 80 |
def __init__( |
| 81 |
self, |
| 82 |
servers: Any = None, |
| 83 |
default_timeout: int = 300, |
| 84 |
key_prefix: str | None = None, |
| 85 |
pool_size: int = 1, |
| 86 |
pool_blocking: bool = True, |
| 87 |
ignore_delete_many_errors: bool = False, |
| 88 |
) -> None: |
| 89 |
CachelibMemcachedCache.__init__( |
| 90 |
self, |
| 91 |
servers=servers, |
| 92 |
default_timeout=default_timeout, |
| 93 |
key_prefix=key_prefix, |
| 94 |
pool_size=pool_size, |
| 95 |
pool_blocking=pool_blocking, |
| 96 |
ignore_delete_many_errors=ignore_delete_many_errors, |
| 97 |
) |
| 98 |
|
| 99 |
@classmethod |
| 100 |
def factory( |
| 101 |
cls, |
| 102 |
app: Flask, |
| 103 |
config: dict[str, Any], |
| 104 |
args: list[Any], |
| 105 |
kwargs: dict[str, Any], |
| 106 |
) -> "MemcachedCache": |
| 107 |
args.append(config["CACHE_MEMCACHED_SERVERS"]) |
| 108 |
kwargs.update(dict(key_prefix=config["CACHE_KEY_PREFIX"])) |
| 109 |
return cls(*args, **kwargs) |
| 110 |
|
| 111 |
|
| 112 |
class SASLMemcachedCache(MemcachedCache): |
| 113 |
def __init__( |
| 114 |
self, |
| 115 |
servers: Any = None, |
| 116 |
default_timeout: int = 300, |
| 117 |
key_prefix: str | None = None, |
| 118 |
username: str | None = None, |
| 119 |
password: str | None = None, |
| 120 |
pool_size: int = 1, |
| 121 |
pool_blocking: bool = True, |
| 122 |
ignore_delete_many_errors: bool = False, |
| 123 |
**kwargs: Any, |
| 124 |
) -> None: |
| 125 |
super().__init__( |
| 126 |
default_timeout=default_timeout, |
| 127 |
ignore_delete_many_errors=ignore_delete_many_errors, |
| 128 |
) |
| 129 |
|
| 130 |
if servers is None: |
| 131 |
servers = ["127.0.0.1:11211"] |
| 132 |
|
| 133 |
import pylibmc # # type: ignore pyright: ignore[reportMissingImports] |
| 134 |
|
| 135 |
client = pylibmc.Client( |
| 136 |
servers, username=username, password=password, binary=True, **kwargs |
| 137 |
) |
| 138 |
pool = pylibmc.ClientPool(client, pool_size) |
| 139 |
reserve = partial(pool.reserve, block=pool_blocking) |
| 140 |
self._client = pool |
| 141 |
self._client_context = reserve |
| 142 |
|
| 143 |
self.key_prefix = key_prefix |
| 144 |
|
| 145 |
@classmethod |
| 146 |
def factory( |
| 147 |
cls, |
| 148 |
app: Flask, |
| 149 |
config: dict[str, Any], |
| 150 |
args: list[Any], |
| 151 |
kwargs: dict[str, Any], |
| 152 |
) -> "SASLMemcachedCache": |
| 153 |
args.append(config["CACHE_MEMCACHED_SERVERS"]) |
| 154 |
kwargs.update( |
| 155 |
dict( |
| 156 |
username=config["CACHE_MEMCACHED_USERNAME"], |
| 157 |
password=config["CACHE_MEMCACHED_PASSWORD"], |
| 158 |
key_prefix=config["CACHE_KEY_PREFIX"], |
| 159 |
) |
| 160 |
) |
| 161 |
return cls(*args, **kwargs) |
| 162 |
|
| 163 |
|
| 164 |
class SpreadSASLMemcachedCache(SASLMemcachedCache): |
| 165 |
"""Simple Subclass of SASLMemcached client that will spread the value |
| 166 |
across multiple keys if they are bigger than a given threshold. |
| 167 |
|
| 168 |
Spreading requires using pickle to store the value, which can significantly |
| 169 |
impact the performance. |
| 170 |
""" |
| 171 |
|
| 172 |
def __init__(self, *args: Any, **kwargs: Any) -> None: |
| 173 |
""" |
| 174 |
Kwargs: |
| 175 |
chunksize (int): max length of a pickled object that can fit in |
| 176 |
memcached (memcache has an upper limit of 1MB for values, |
| 177 |
default: 1048448) |
| 178 |
""" |
| 179 |
self.chunksize = kwargs.get("chunksize", 1048448) |
| 180 |
self.maxchunk = kwargs.get("maxchunk", 32) |
| 181 |
super().__init__(*args, **kwargs) |
| 182 |
|
| 183 |
@classmethod |
| 184 |
def factory( |
| 185 |
cls, |
| 186 |
app: Flask, |
| 187 |
config: dict[str, Any], |
| 188 |
args: list[Any], |
| 189 |
kwargs: dict[str, Any], |
| 190 |
) -> "SpreadSASLMemcachedCache": |
| 191 |
args.append(config["CACHE_MEMCACHED_SERVERS"]) |
| 192 |
kwargs.update( |
| 193 |
dict( |
| 194 |
username=config.get("CACHE_MEMCACHED_USERNAME"), |
| 195 |
password=config.get("CACHE_MEMCACHED_PASSWORD"), |
| 196 |
key_prefix=config.get("CACHE_KEY_PREFIX"), |
| 197 |
) |
| 198 |
) |
| 199 |
|
| 200 |
return cls(*args, **kwargs) |
| 201 |
|
| 202 |
def delete(self, key: str) -> Any: |
| 203 |
for skey in self._genkeys(key): |
| 204 |
super().delete(skey) |
| 205 |
|
| 206 |
def set( |
| 207 |
self, |
| 208 |
key: str, |
| 209 |
value: Any, |
| 210 |
timeout: _Timeout | None = None, |
| 211 |
chunk: bool = True, |
| 212 |
) -> bool | None: |
| 213 |
"""Set a value in cache, potentially spreading it across multiple key. |
| 214 |
|
| 215 |
:param key: The cache key. |
| 216 |
:param value: The value to cache. |
| 217 |
:param timeout: The timeout after which the cache will be invalidated. |
| 218 |
:param chunk: If set to `False`, then spreading across multiple keys |
| 219 |
is disabled. This can be faster, but it will fail if |
| 220 |
the value is bigger than the chunks. It requires you |
| 221 |
to get back the object by specifying that it is not |
| 222 |
spread. |
| 223 |
""" |
| 224 |
if chunk: |
| 225 |
self._set(key, value, timeout=timeout) |
| 226 |
return None |
| 227 |
else: |
| 228 |
return super().set(key, value, timeout=timeout) |
| 229 |
|
| 230 |
def _set(self, key: str, value: Any, timeout: _Timeout | None = None) -> None: |
| 231 |
# pickling/unpickling add an overhead, |
| 232 |
# I didn't found a good way to avoid pickling/unpickling if |
| 233 |
# key is smaller than chunksize, because in case or <werkzeug.requests> |
| 234 |
# getting the length consume the data iterator. |
| 235 |
serialized = pickle.dumps(value, 2) |
| 236 |
values = {} |
| 237 |
len_ser = len(serialized) |
| 238 |
chks = range(0, len_ser, self.chunksize) |
| 239 |
|
| 240 |
if len(chks) > self.maxchunk: |
| 241 |
raise ValueError(f"Cannot store value in less than {self.maxchunk} keys") |
| 242 |
|
| 243 |
for i in chks: |
| 244 |
values[f"{key}.{i // self.chunksize}"] = serialized[i : i + self.chunksize] |
| 245 |
|
| 246 |
super().set_many(values, timeout) |
| 247 |
|
| 248 |
def get(self, key: str, chunk: bool = True) -> Any: |
| 249 |
"""Get a cached value. |
| 250 |
|
| 251 |
:param chunk: If set to ``False``, it will return a cached value |
| 252 |
that is spread across multiple keys. |
| 253 |
""" |
| 254 |
if chunk: |
| 255 |
return self._get(key) |
| 256 |
else: |
| 257 |
return super().get(key) |
| 258 |
|
| 259 |
def _genkeys(self, key: str) -> list[str]: |
| 260 |
return [f"{key}.{i}" for i in range(self.maxchunk)] |
| 261 |
|
| 262 |
def _get(self, key: str) -> Any: |
| 263 |
to_get = [f"{key}.{i}" for i in range(self.maxchunk)] |
| 264 |
result = super().get_many(*to_get) |
| 265 |
serialized = b"".join(v for v in result if v is not None) |
| 266 |
|
| 267 |
if not serialized: |
| 268 |
return None |
| 269 |
|
| 270 |
return pickle.loads(serialized) |