| 1 |
""" |
| 2 |
flask_caching |
| 3 |
~~~~~~~~~~~~~ |
| 4 |
|
| 5 |
Adds cache support to your application. |
| 6 |
|
| 7 |
:copyright: (c) 2010 by Thadeus Burgess. |
| 8 |
:license: BSD, see LICENSE for more details. |
| 9 |
""" |
| 10 |
|
| 11 |
import base64 |
| 12 |
import functools |
| 13 |
import hashlib |
| 14 |
import inspect |
| 15 |
import logging |
| 16 |
import uuid |
| 17 |
import warnings |
| 18 |
from collections import OrderedDict |
| 19 |
from collections.abc import Callable |
| 20 |
from collections.abc import Iterable |
| 21 |
from typing import Any |
| 22 |
from typing import cast |
| 23 |
from typing import Concatenate |
| 24 |
from typing import overload |
| 25 |
from typing import ParamSpec |
| 26 |
from typing import Protocol |
| 27 |
from typing import TypeAlias |
| 28 |
from typing import TypeVar |
| 29 |
|
| 30 |
from cachelib.serializers import BaseSerializer |
| 31 |
from flask import current_app |
| 32 |
from flask import Flask |
| 33 |
from flask import g |
| 34 |
from flask import request |
| 35 |
from flask import Response |
| 36 |
from flask import url_for |
| 37 |
from werkzeug.exceptions import HTTPException |
| 38 |
from werkzeug.utils import import_string |
| 39 |
|
| 40 |
from .backends.base import BaseCache |
| 41 |
from .backends.simplecache import SimpleCache |
| 42 |
from .signals import cache_memoize_hit as cache_memoize_hit |
| 43 |
from .signals import cache_memoize_miss as cache_memoize_miss |
| 44 |
from .signals import cache_view_hit as cache_view_hit |
| 45 |
from .signals import cache_view_miss as cache_view_miss |
| 46 |
from .utils import _QueryArgs |
| 47 |
from .utils import _Timeout |
| 48 |
from .utils import function_namespace |
| 49 |
from .utils import get_arg_default |
| 50 |
from .utils import get_arg_names |
| 51 |
from .utils import get_id |
| 52 |
from .utils import join_generator |
| 53 |
from .utils import make_template_fragment_key as make_template_fragment_key |
| 54 |
from .utils import normalize_timeout |
| 55 |
from .utils import query_args_as_pairs |
| 56 |
from .utils import wants_args |
| 57 |
from .utils import wants_extra_args |
| 58 |
|
| 59 |
logger = logging.getLogger(__name__) |
| 60 |
|
| 61 |
|
| 62 |
# The initial version timeout of a memoize version key. Will be overwritten on the first |
| 63 |
# write with the memoize value timeout |
| 64 |
VERSION_TIMEOUT = 0 |
| 65 |
|
| 66 |
SUPPORTED_HASH_FUNCTIONS = [ |
| 67 |
hashlib.sha1, |
| 68 |
hashlib.sha224, |
| 69 |
hashlib.sha256, |
| 70 |
hashlib.sha384, |
| 71 |
hashlib.sha512, |
| 72 |
hashlib.md5, |
| 73 |
] |
| 74 |
|
| 75 |
|
| 76 |
P = ParamSpec("P") |
| 77 |
# The parameters left over after ``__get__`` binds the instance. |
| 78 |
P2 = ParamSpec("P2") |
| 79 |
R = TypeVar("R") |
| 80 |
T = TypeVar("T") |
| 81 |
# ``uncached`` is read-only on the bound protocols, so their instance and |
| 82 |
# return types are contravariant and covariant respectively. |
| 83 |
T_co = TypeVar("T_co", covariant=True) |
| 84 |
T_contra = TypeVar("T_contra", contravariant=True) |
| 85 |
|
| 86 |
|
| 87 |
class _BoundCachedFunction(Protocol[T_contra, P, T_co]): |
| 88 |
"""The type of a :meth:`Cache.cached` method accessed on an instance.""" |
| 89 |
|
| 90 |
cache_timeout: _Timeout | None |
| 91 |
make_cache_key: Callable[..., str] |
| 92 |
|
| 93 |
@property |
| 94 |
def uncached(self) -> Callable[Concatenate[T_contra, P], T_co]: ... |
| 95 |
|
| 96 |
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T_co: ... |
| 97 |
|
| 98 |
|
| 99 |
class _CachedFunction(Protocol[P, R]): |
| 100 |
"""The type of the callable returned by :meth:`Cache.cached`.""" |
| 101 |
|
| 102 |
uncached: Callable[P, R] |
| 103 |
cache_timeout: _Timeout | None |
| 104 |
make_cache_key: Callable[..., str] |
| 105 |
|
| 106 |
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: ... |
| 107 |
|
| 108 |
# The decorator returns a function, so decorating a method keeps working |
| 109 |
# at runtime. Without ``__get__`` type checkers see a plain attribute |
| 110 |
# instead of a descriptor and never bind ``self``. |
| 111 |
@overload |
| 112 |
def __get__( |
| 113 |
self, instance: None, owner: type | None = None, / |
| 114 |
) -> "_CachedFunction[P, R]": ... |
| 115 |
@overload |
| 116 |
def __get__( |
| 117 |
self: "_CachedFunction[Concatenate[T, P2], R]", |
| 118 |
instance: T, |
| 119 |
owner: type | None = None, |
| 120 |
/, |
| 121 |
) -> _BoundCachedFunction[T, P2, R]: ... |
| 122 |
def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... |
| 123 |
|
| 124 |
|
| 125 |
class _BoundMemoizedFunction(Protocol[T_contra, P, T_co]): |
| 126 |
"""The type of a :meth:`Cache.memoize` method accessed on an instance.""" |
| 127 |
|
| 128 |
cache_timeout: _Timeout | None |
| 129 |
make_cache_key: Callable[..., str] |
| 130 |
delete_memoized: Callable[[], None] |
| 131 |
|
| 132 |
@property |
| 133 |
def uncached(self) -> Callable[Concatenate[T_contra, P], T_co]: ... |
| 134 |
|
| 135 |
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T_co: ... |
| 136 |
|
| 137 |
|
| 138 |
class _MemoizedFunction(Protocol[P, R]): |
| 139 |
"""The type of the callable returned by :meth:`Cache.memoize`.""" |
| 140 |
|
| 141 |
uncached: Callable[P, R] |
| 142 |
cache_timeout: _Timeout | None |
| 143 |
make_cache_key: Callable[..., str] |
| 144 |
delete_memoized: Callable[[], None] |
| 145 |
|
| 146 |
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: ... |
| 147 |
|
| 148 |
@overload |
| 149 |
def __get__( |
| 150 |
self, instance: None, owner: type | None = None, / |
| 151 |
) -> "_MemoizedFunction[P, R]": ... |
| 152 |
@overload |
| 153 |
def __get__( |
| 154 |
self: "_MemoizedFunction[Concatenate[T, P2], R]", |
| 155 |
instance: T, |
| 156 |
owner: type | None = None, |
| 157 |
/, |
| 158 |
) -> _BoundMemoizedFunction[T, P2, R]: ... |
| 159 |
def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... |
| 160 |
|
| 161 |
|
| 162 |
# A memoized function, however it was reached: a plain function, a method |
| 163 |
# accessed on the class, or a method accessed on an instance. |
| 164 |
_AnyMemoizedFunction: TypeAlias = ( |
| 165 |
"_MemoizedFunction[..., Any] | _BoundMemoizedFunction[Any, ..., Any]" |
| 166 |
) |
| 167 |
|
| 168 |
_AnyCachedFunction: TypeAlias = ( |
| 169 |
"_CachedFunction[..., Any] | _BoundCachedFunction[Any, ..., Any]" |
| 170 |
) |
| 171 |
|
| 172 |
|
| 173 |
class CachedResponse(Response): |
| 174 |
""" |
| 175 |
views wraped by @cached can return this (which inherits from flask.Response) |
| 176 |
to override the cache TTL dynamically |
| 177 |
""" |
| 178 |
|
| 179 |
timeout: int | None = None |
| 180 |
|
| 181 |
def __init__(self, response: Response, timeout: _Timeout | None) -> None: |
| 182 |
# ``CachedResponse`` adopts the state of an existing Response in |
| 183 |
# place rather than calling ``Response.__init__``; copying |
| 184 |
# ``__dict__`` preserves headers, status and body without having |
| 185 |
# to round-trip the response through Werkzeug's constructor. |
| 186 |
self.__dict__ = response.__dict__ |
| 187 |
self.timeout = normalize_timeout(timeout) |
| 188 |
|
| 189 |
|
| 190 |
class Cache: |
| 191 |
"""This class is used to control the cache objects.""" |
| 192 |
|
| 193 |
def __init__( |
| 194 |
self, |
| 195 |
app: Flask | None = None, |
| 196 |
with_jinja2_ext: bool = True, |
| 197 |
config: dict[str, Any] | None = None, |
| 198 |
) -> None: |
| 199 |
if not (config is None or isinstance(config, dict)): |
| 200 |
raise ValueError("`config` must be an instance of dict or None") |
| 201 |
|
| 202 |
self.with_jinja2_ext = with_jinja2_ext |
| 203 |
self.config = config |
| 204 |
|
| 205 |
self.source_check = None |
| 206 |
self.hash_method: Callable[..., Any] | None = None |
| 207 |
self.serializer: BaseSerializer | None = None |
| 208 |
self.enable_signals = False |
| 209 |
|
| 210 |
if app is not None: |
| 211 |
self.init_app(app, config) |
| 212 |
|
| 213 |
def init_app(self, app: Flask, config: dict[str, Any] | None = None) -> None: |
| 214 |
"""This is used to initialize cache with your app object""" |
| 215 |
if not (config is None or isinstance(config, dict)): |
| 216 |
raise ValueError("`config` must be an instance of dict or None") |
| 217 |
|
| 218 |
#: Ref PR #44. |
| 219 |
#: Do not set self.app in the case a single instance of the Cache |
| 220 |
#: object is being used for multiple app instances. |
| 221 |
#: Example use case would be Cache shipped as part of a blueprint |
| 222 |
#: or utility library. |
| 223 |
|
| 224 |
base_config = app.config.copy() |
| 225 |
if self.config: |
| 226 |
base_config.update(self.config) |
| 227 |
if config: |
| 228 |
base_config.update(config) |
| 229 |
config = base_config |
| 230 |
|
| 231 |
config.setdefault("CACHE_DEFAULT_TIMEOUT", 300) |
| 232 |
config.setdefault("CACHE_IGNORE_ERRORS", False) |
| 233 |
config.setdefault("CACHE_THRESHOLD", 500) |
| 234 |
config.setdefault("CACHE_KEY_PREFIX", "flask_cache_") |
| 235 |
config.setdefault("CACHE_MEMCACHED_SERVERS", None) |
| 236 |
config.setdefault("CACHE_DIR", None) |
| 237 |
config.setdefault("CACHE_FILE_HASH_METHOD", hashlib.sha256) |
| 238 |
config.setdefault("CACHE_HASH_METHOD", hashlib.sha256) |
| 239 |
config.setdefault("CACHE_OPTIONS", None) |
| 240 |
config.setdefault("CACHE_ARGS", []) |
| 241 |
config.setdefault("CACHE_TYPE", "NullCache") |
| 242 |
config.setdefault("CACHE_NO_NULL_WARNING", False) |
| 243 |
config.setdefault("CACHE_SOURCE_CHECK", False) |
| 244 |
config.setdefault("CACHE_ENABLE_SIGNALS", False) |
| 245 |
config.setdefault("CACHE_SERIALIZER", None) |
| 246 |
|
| 247 |
if config["CACHE_TYPE"] == "NullCache" and not config["CACHE_NO_NULL_WARNING"]: |
| 248 |
warnings.warn( |
| 249 |
"Flask-Caching: CACHE_TYPE is set to NullCache, " |
| 250 |
"caching is effectively disabled.", |
| 251 |
stacklevel=2, |
| 252 |
) |
| 253 |
|
| 254 |
if config["CACHE_TYPE"] == "FileSystemCache" and config["CACHE_DIR"] is None: |
| 255 |
warnings.warn( |
| 256 |
f"Flask-Caching: CACHE_TYPE is set to {config['CACHE_TYPE']} but no " |
| 257 |
"CACHE_DIR is set.", |
| 258 |
stacklevel=2, |
| 259 |
) |
| 260 |
|
| 261 |
self.source_check = config["CACHE_SOURCE_CHECK"] |
| 262 |
self.enable_signals = config["CACHE_ENABLE_SIGNALS"] |
| 263 |
# Validated here rather than lazily so that a bad hash method is |
| 264 |
# reported at startup instead of on the first cached call. |
| 265 |
if not callable(config["CACHE_HASH_METHOD"]): |
| 266 |
raise ValueError( |
| 267 |
"`CACHE_HASH_METHOD` must be a hash constructor, for example " |
| 268 |
f"`hashlib.sha256`, not {config['CACHE_HASH_METHOD']!r}" |
| 269 |
) |
| 270 |
self.hash_method = config["CACHE_HASH_METHOD"] |
| 271 |
self.serializer = self._get_serializer(config["CACHE_SERIALIZER"]) |
| 272 |
|
| 273 |
if self.with_jinja2_ext: |
| 274 |
from .jinja2ext import CacheExtension |
| 275 |
from .jinja2ext import JINJA_CACHE_ATTR_NAME |
| 276 |
|
| 277 |
setattr(app.jinja_env, JINJA_CACHE_ATTR_NAME, self) |
| 278 |
app.jinja_env.add_extension(CacheExtension) |
| 279 |
|
| 280 |
self._set_cache(app, config) |
| 281 |
|
| 282 |
def _set_cache(self, app: Flask, config: dict[str, Any]) -> None: |
| 283 |
import_me = config["CACHE_TYPE"] |
| 284 |
if "." not in import_me: |
| 285 |
import_me = "flask_caching.backends." + import_me |
| 286 |
|
| 287 |
cache_factory = import_string(import_me) |
| 288 |
cache_args = config["CACHE_ARGS"][:] |
| 289 |
cache_options = { |
| 290 |
"default_timeout": config["CACHE_DEFAULT_TIMEOUT"], |
| 291 |
"ignore_delete_many_errors": config["CACHE_IGNORE_ERRORS"], |
| 292 |
} |
| 293 |
|
| 294 |
if isinstance(cache_factory, type) and issubclass(cache_factory, BaseCache): |
| 295 |
cache_factory = cache_factory.factory |
| 296 |
|
| 297 |
if config["CACHE_OPTIONS"]: |
| 298 |
cache_options.update(config["CACHE_OPTIONS"]) |
| 299 |
|
| 300 |
cache_options["default_timeout"] = normalize_timeout( |
| 301 |
cache_options["default_timeout"] |
| 302 |
) |
| 303 |
|
| 304 |
# Backends that are not created from cachelib read the timeout from |
| 305 |
# config instead of cache_options. |
| 306 |
config["CACHE_DEFAULT_TIMEOUT"] = cache_options["default_timeout"] |
| 307 |
|
| 308 |
if not hasattr(app, "extensions"): |
| 309 |
app.extensions = {} |
| 310 |
|
| 311 |
app.extensions.setdefault("cache", {}) |
| 312 |
if import_me.find("cachelib") > -1: |
| 313 |
cache = cache_factory(*cache_args, **cache_options) |
| 314 |
else: |
| 315 |
cache = cache_factory(app, config, cache_args, cache_options) |
| 316 |
|
| 317 |
if self.serializer is not None: |
| 318 |
if hasattr(cache, "serializer"): |
| 319 |
cache.serializer = self.serializer # pyright: ignore[reportAttributeAccessIssue] |
| 320 |
else: |
| 321 |
warnings.warn( |
| 322 |
f"CACHE_SERIALIZER is set but {type(cache).__name__} does not use" |
| 323 |
"a serializer.", |
| 324 |
stacklevel=2, |
| 325 |
) |
| 326 |
|
| 327 |
app.extensions["cache"][self] = cache |
| 328 |
self.app = app |
| 329 |
|
| 330 |
def _get_serializer(self, serializer: Any) -> BaseSerializer | None: |
| 331 |
"""Returns the serializer instance for the caching backend. |
| 332 |
If None, it will use the default one. |
| 333 |
""" |
| 334 |
if serializer is None: |
| 335 |
return None |
| 336 |
|
| 337 |
if isinstance(serializer, type) and issubclass(serializer, BaseSerializer): |
| 338 |
try: |
| 339 |
return serializer() |
| 340 |
except TypeError as e: |
| 341 |
raise ValueError( |
| 342 |
f"Couldn't instantiate serializer: {serializer!r}!" |
| 343 |
) from e |
| 344 |
|
| 345 |
if not isinstance(serializer, BaseSerializer): |
| 346 |
raise ValueError( |
| 347 |
"`CACHE_SERIALIZER` must be a `cachelib.serializers.BaseSerializer` " |
| 348 |
"subclass or instance!" |
| 349 |
) |
| 350 |
|
| 351 |
return serializer |
| 352 |
|
| 353 |
def _get_hash_method( |
| 354 |
self, hash_method: Callable[..., Any] | None |
| 355 |
) -> Callable[..., Any]: |
| 356 |
"""Returns the hash method for the cache keys. Defaults to hashlib.sha256""" |
| 357 |
if hash_method is not None: |
| 358 |
return hash_method |
| 359 |
return self.hash_method or hashlib.sha256 |
| 360 |
|
| 361 |
def _get_source_check(self, source_check: bool | None) -> bool | None: |
| 362 |
"""Resolve whether the function's source belongs in the cache key.""" |
| 363 |
if source_check is not None: |
| 364 |
return source_check |
| 365 |
return self.source_check |
| 366 |
|
| 367 |
def _call_fn(self, fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: |
| 368 |
ensure_sync = getattr(self.app, "ensure_sync", None) |
| 369 |
if ensure_sync is not None: |
| 370 |
return ensure_sync(fn)(*args, **kwargs) |
| 371 |
return fn(*args, **kwargs) |
| 372 |
|
| 373 |
def _call_fn_or_exception( |
| 374 |
self, fn: Callable[..., Any], *args: Any, **kwargs: Any |
| 375 |
) -> Any: |
| 376 |
"""Returns an ``HTTPException`` instead of propagating it.""" |
| 377 |
try: |
| 378 |
return self._call_fn(fn, *args, **kwargs) |
| 379 |
except HTTPException as e: |
| 380 |
return e |
| 381 |
|
| 382 |
@property |
| 383 |
def cache(self) -> SimpleCache: |
| 384 |
"""The backend instance the proxy methods delegate to. Use this to |
| 385 |
reach backend specific functionality that ``Cache`` does not proxy. |
| 386 |
Requires an application context. |
| 387 |
""" |
| 388 |
app = current_app or self.app |
| 389 |
return cast("SimpleCache", app.extensions["cache"][self]) |
| 390 |
|
| 391 |
def get(self, *args: Any, **kwargs: Any) -> Any: |
| 392 |
"""Proxy function for internal cache object.""" |
| 393 |
return self.cache.get(*args, **kwargs) |
| 394 |
|
| 395 |
def has(self, *args: Any, **kwargs: Any) -> bool: |
| 396 |
"""Proxy function for internal cache object.""" |
| 397 |
return self.cache.has(*args, **kwargs) |
| 398 |
|
| 399 |
def set(self, *args: Any, **kwargs: Any) -> bool | None: |
| 400 |
"""Proxy function for internal cache object.""" |
| 401 |
return self.cache.set(*args, **kwargs) |
| 402 |
|
| 403 |
def add(self, *args: Any, **kwargs: Any) -> bool: |
| 404 |
"""Proxy function for internal cache object.""" |
| 405 |
return self.cache.add(*args, **kwargs) |
| 406 |
|
| 407 |
def delete(self, *args: Any, **kwargs: Any) -> bool: |
| 408 |
"""Proxy function for internal cache object.""" |
| 409 |
return self.cache.delete(*args, **kwargs) |
| 410 |
|
| 411 |
def delete_many(self, *args: Any, **kwargs: Any) -> list[str]: |
| 412 |
"""Proxy function for internal cache object.""" |
| 413 |
return self.cache.delete_many(*args, **kwargs) |
| 414 |
|
| 415 |
def clear(self) -> bool: |
| 416 |
"""Proxy function for internal cache object.""" |
| 417 |
return self.cache.clear() |
| 418 |
|
| 419 |
def get_many(self, *args: Any, **kwargs: Any) -> list[Any]: |
| 420 |
"""Proxy function for internal cache object.""" |
| 421 |
return self.cache.get_many(*args, **kwargs) |
| 422 |
|
| 423 |
def set_many(self, *args: Any, **kwargs: Any) -> list[Any]: |
| 424 |
"""Proxy function for internal cache object.""" |
| 425 |
return self.cache.set_many(*args, **kwargs) |
| 426 |
|
| 427 |
def get_dict(self, *args: Any, **kwargs: Any) -> dict[str, Any]: |
| 428 |
"""Proxy function for internal cache object.""" |
| 429 |
return self.cache.get_dict(*args, **kwargs) |
| 430 |
|
| 431 |
def unlink(self, *args: Any, **kwargs: Any) -> list[str]: |
| 432 |
"""Proxy function for internal cache object |
| 433 |
only support Redis |
| 434 |
""" |
| 435 |
unlink = getattr(self.cache, "unlink", None) |
| 436 |
if unlink is not None and callable(unlink): |
| 437 |
return cast("list[str]", unlink(*args, **kwargs)) |
| 438 |
return self.delete_many(*args, **kwargs) |
| 439 |
|
| 440 |
def cached( |
| 441 |
self, |
| 442 |
timeout: _Timeout | None = None, |
| 443 |
key_prefix: str | Callable[[], str] = "view/%s", |
| 444 |
unless: Callable[..., Any] | None = None, |
| 445 |
forced_update: Callable[..., Any] | None = None, |
| 446 |
is_stale: Callable[..., Any] | None = None, |
| 447 |
response_filter: Callable[..., Any] | None = None, |
| 448 |
query_string: bool = False, |
| 449 |
hash_method: Callable[..., Any] | None = None, |
| 450 |
cache_none: bool = False, |
| 451 |
make_cache_key: Callable[..., Any] | None = None, |
| 452 |
source_check: bool | None = None, |
| 453 |
response_hit_indication: bool | None = False, |
| 454 |
) -> Callable[[Callable[P, R]], _CachedFunction[P, R]]: |
| 455 |
"""Decorator. Use this to cache a function. By default the cache key |
| 456 |
is `view/request.path`. You are able to use this decorator with any |
| 457 |
function by changing the `key_prefix`. If the token `%s` is located |
| 458 |
within the `key_prefix` then it will replace that with `request.path` |
| 459 |
|
| 460 |
Example:: |
| 461 |
|
| 462 |
# An example view function |
| 463 |
@cache.cached(timeout=50) |
| 464 |
def big_foo(): |
| 465 |
return big_bar_calc() |
| 466 |
|
| 467 |
# An example misc function to cache. |
| 468 |
@cache.cached(key_prefix='MyCachedList') |
| 469 |
def get_list(): |
| 470 |
return [random.randrange(0, 1) for i in range(50000)] |
| 471 |
|
| 472 |
my_list = get_list() |
| 473 |
|
| 474 |
.. note:: |
| 475 |
|
| 476 |
You MUST have a request context to actually called any functions |
| 477 |
that are cached. |
| 478 |
|
| 479 |
.. versionadded:: 0.4 |
| 480 |
The returned decorated function now has three function attributes |
| 481 |
assigned to it. These attributes are readable/writable. |
| 482 |
|
| 483 |
**uncached** |
| 484 |
The original undecorated function |
| 485 |
|
| 486 |
**cache_timeout** |
| 487 |
The cache timeout value for this function. For a |
| 488 |
custom value to take affect, this must be set before the |
| 489 |
function is called. |
| 490 |
|
| 491 |
**make_cache_key** |
| 492 |
A function used in generating the cache_key used. |
| 493 |
|
| 494 |
readable and writable |
| 495 |
|
| 496 |
Outside of a request context, pass ``path`` to build the |
| 497 |
key for a given ``request.path`` and, for |
| 498 |
``query_string=True``, ``query_args`` to build the key for |
| 499 |
a given query string:: |
| 500 |
|
| 501 |
key = view.make_cache_key( |
| 502 |
path="/works", query_args="limit=15&mock=true" |
| 503 |
) |
| 504 |
cache.delete(key) |
| 505 |
|
| 506 |
``query_args`` accepts a query string, a mapping or an |
| 507 |
iterable of ``(key, value)`` pairs. See |
| 508 |
:meth:`delete_cached` for the shorthand. |
| 509 |
|
| 510 |
:param timeout: Default None. If set to an integer, will cache for that |
| 511 |
amount of time. Unit of time is in seconds. A |
| 512 |
``datetime.timedelta`` is also accepted and is rounded |
| 513 |
up to whole seconds. |
| 514 |
|
| 515 |
:param key_prefix: Default 'view/%(request.path)s'. Beginning key to . |
| 516 |
use for the cache key. `request.path` will be the |
| 517 |
actual request path, or in cases where the |
| 518 |
`make_cache_key`-function is called from other |
| 519 |
views it will be the expected URL for the view |
| 520 |
as generated by Flask's `url_for()`. |
| 521 |
|
| 522 |
.. versionadded:: 0.3.4 |
| 523 |
Can optionally be a callable which takes |
| 524 |
no arguments but returns a string that will |
| 525 |
be used as the cache_key. |
| 526 |
|
| 527 |
:param unless: Default None. Cache will *always* execute the caching |
| 528 |
facilities unless this callable is true. |
| 529 |
This will bypass the caching entirely. |
| 530 |
|
| 531 |
:param forced_update: Default None. If this callable is true, |
| 532 |
cache value will be updated regardless cache |
| 533 |
is expired or not. Useful for background |
| 534 |
renewal of cached functions. |
| 535 |
|
| 536 |
:param is_stale: Default None. Called on a cache hit with the cached |
| 537 |
value as its first argument. If it is true the cached |
| 538 |
value will be recomputed. If the callable accepts more |
| 539 |
than one argument, the calls own arguments are passed |
| 540 |
after the cached value. |
| 541 |
|
| 542 |
:param response_filter: Default None. If not None, the callable is |
| 543 |
invoked after the cached function evaluation, |
| 544 |
and is given one argument, the response |
| 545 |
content. If the callable returns False, the |
| 546 |
content will not be cached. Useful to prevent |
| 547 |
caching of code 500 responses. |
| 548 |
|
| 549 |
:param query_string: Default False. When True, the cache key |
| 550 |
used will be the result of hashing the |
| 551 |
ordered query string parameters. This |
| 552 |
avoids creating different caches for |
| 553 |
the same query just because the parameters |
| 554 |
were passed in a different order. See |
| 555 |
_make_cache_key_query_string() for more |
| 556 |
details. |
| 557 |
|
| 558 |
.. versionchanged:: 2.5.0 |
| 559 |
Include ``key_prefix`` when building query string cache keys. |
| 560 |
|
| 561 |
:param hash_method: Default None. If None will use the value set by |
| 562 |
``CACHE_HASH_METHOD``, which defaults to |
| 563 |
``hashlib.sha256``. The hash method used to |
| 564 |
generate the keys for cached results. |
| 565 |
:param cache_none: Default False. If set to True, add a key exists |
| 566 |
check when cache.get returns None. This will likely |
| 567 |
lead to wrongly returned None values in concurrent |
| 568 |
situations and is not recommended to use. |
| 569 |
:param make_cache_key: Default None. If set to a callable object, |
| 570 |
it will be called to generate the cache key |
| 571 |
|
| 572 |
:param source_check: Default None. If None will use the value set by |
| 573 |
CACHE_SOURCE_CHECK. |
| 574 |
If True, include the function's source code in the |
| 575 |
hash to avoid using cached values when the source |
| 576 |
code has changed and the input values remain the |
| 577 |
same. This ensures that the cache_key will be |
| 578 |
formed with the function's source code hash in |
| 579 |
addition to other parameters that may be included |
| 580 |
in the formation of the key. |
| 581 |
|
| 582 |
:param response_hit_indication: Default False. |
| 583 |
If True, it will add to response header field 'hit_cache' |
| 584 |
if used cache. |
| 585 |
|
| 586 |
.. versionchanged:: 2.5.0 |
| 587 |
A ``werkzeug.exceptions.HTTPException`` raised by the decorated |
| 588 |
function, for example through Flask's ``abort()``, is now cached |
| 589 |
like a returned response and re-raised on a cache hit. Use |
| 590 |
``response_filter``, which is given the exception's response, to |
| 591 |
keep it out of the cache. |
| 592 |
""" |
| 593 |
|
| 594 |
def decorator(f: Callable[P, R]) -> _CachedFunction[P, R]: |
| 595 |
@functools.wraps(f) |
| 596 |
def decorated_function(*args: Any, **kwargs: Any) -> Any: |
| 597 |
#: Bypass the cache entirely. |
| 598 |
if self._bypass_cache(unless, f, *args, **kwargs): |
| 599 |
return self._call_fn(f, *args, **kwargs) |
| 600 |
|
| 601 |
try: |
| 602 |
if make_cache_key is not None and callable(make_cache_key): |
| 603 |
cache_key = make_cache_key(*args, **kwargs) |
| 604 |
else: |
| 605 |
cache_key = cached_fn.make_cache_key( |
| 606 |
*args, use_request=True, **kwargs |
| 607 |
) |
| 608 |
|
| 609 |
if self._forced_update(forced_update, *args, **kwargs): |
| 610 |
rv = None |
| 611 |
found = False |
| 612 |
else: |
| 613 |
rv = self.get(cache_key) |
| 614 |
found = True |
| 615 |
|
| 616 |
# If the value returned by cache.get() is None, it |
| 617 |
# might be because the key is not found in the cache |
| 618 |
# or because the cached value is actually None |
| 619 |
if rv is None: |
| 620 |
# If we're sure we don't need to cache None values |
| 621 |
# (cache_none=False), don't bother checking for |
| 622 |
# key existence, as it can lead to false positives |
| 623 |
# if a concurrent call already cached the |
| 624 |
# key between steps. This would cause us to |
| 625 |
# return None when we shouldn't |
| 626 |
if not cache_none: |
| 627 |
found = False |
| 628 |
else: |
| 629 |
found = self.has(cache_key) |
| 630 |
|
| 631 |
if found and self._is_stale(is_stale, rv, *args, **kwargs): |
| 632 |
rv = None |
| 633 |
found = False |
| 634 |
except Exception: |
| 635 |
if self.app.debug: |
| 636 |
raise |
| 637 |
logger.exception("Exception possibly due to cache backend.") |
| 638 |
return self._call_fn(f, *args, **kwargs) |
| 639 |
if found and self.app.debug: |
| 640 |
logger.info(f"Cache used for key: {cache_key}") |
| 641 |
if response_hit_indication: |
| 642 |
g.flask_caching_hit_cache = found |
| 643 |
|
| 644 |
def apply_caching(response: Response) -> Response: |
| 645 |
if g.get("flask_caching_hit_cache"): |
| 646 |
response.headers["hit_cache"] = g.flask_caching_hit_cache |
| 647 |
return response |
| 648 |
|
| 649 |
after_request_funcs = self.app.after_request_funcs[None] |
| 650 |
if not any( |
| 651 |
getattr(func, "__name__", None) == "apply_caching" |
| 652 |
for func in after_request_funcs |
| 653 |
): |
| 654 |
after_request_funcs.append(apply_caching) |
| 655 |
|
| 656 |
if self.enable_signals: |
| 657 |
signal = cache_view_hit if found else cache_view_miss |
| 658 |
signal.send( |
| 659 |
cache=self, cache_key=cache_key, args=args, kwargs=kwargs |
| 660 |
) |
| 661 |
|
| 662 |
if found and isinstance(rv, HTTPException): |
| 663 |
raise rv |
| 664 |
|
| 665 |
if not found: |
| 666 |
rv = self._call_fn_or_exception(f, *args, **kwargs) |
| 667 |
if inspect.isgenerator(rv): |
| 668 |
rv = join_generator(rv) |
| 669 |
|
| 670 |
if response_filter is None or response_filter( |
| 671 |
rv.get_response() if isinstance(rv, HTTPException) else rv |
| 672 |
): |
| 673 |
cache_timeout = normalize_timeout(cached_fn.cache_timeout) |
| 674 |
if isinstance(rv, CachedResponse): |
| 675 |
cache_timeout = rv.timeout or cache_timeout |
| 676 |
|
| 677 |
try: |
| 678 |
self.set( |
| 679 |
cache_key, |
| 680 |
rv, |
| 681 |
timeout=cache_timeout, |
| 682 |
) |
| 683 |
except Exception: |
| 684 |
if self.app.debug: |
| 685 |
raise |
| 686 |
logger.exception("Exception possibly due to cache backend.") |
| 687 |
|
| 688 |
if isinstance(rv, HTTPException): |
| 689 |
raise rv |
| 690 |
return rv |
| 691 |
|
| 692 |
def default_make_cache_key(*args: Any, **kwargs: Any) -> str: |
| 693 |
# Convert non-keyword arguments (which is the way |
| 694 |
# `make_cache_key` expects them) to keyword arguments |
| 695 |
# (the way `url_for` expects them) |
| 696 |
argspec_args = get_arg_names(f) |
| 697 |
|
| 698 |
for arg_name, arg in zip(argspec_args, args, strict=False): |
| 699 |
kwargs[arg_name] = arg |
| 700 |
|
| 701 |
use_request = kwargs.pop("use_request", False) |
| 702 |
if use_request: |
| 703 |
# The remaining kwargs are the view arguments of the |
| 704 |
# current request. View arguments named ``path`` or |
| 705 |
# ``query_args`` must not be mistaken for the explicit |
| 706 |
# arguments of the same name. |
| 707 |
path = None |
| 708 |
query_args = None |
| 709 |
else: |
| 710 |
path = kwargs.pop("path", None) |
| 711 |
query_args = kwargs.pop("query_args", None) |
| 712 |
return _make_cache_key( |
| 713 |
args, |
| 714 |
kwargs, |
| 715 |
use_request=use_request, |
| 716 |
path=path, |
| 717 |
query_args=query_args, |
| 718 |
) |
| 719 |
|
| 720 |
def _make_cache_key_query_string( |
| 721 |
path: str | None = None, |
| 722 |
query_args: _QueryArgs | None = None, |
| 723 |
) -> str: |
| 724 |
"""Create consistent keys for query string arguments. |
| 725 |
|
| 726 |
Produces the same cache key regardless of argument order, e.g., |
| 727 |
both `?limit=10&offset=20` and `?offset=20&limit=10` will |
| 728 |
always produce the same exact cache key. |
| 729 |
|
| 730 |
If func is provided and is callable it will be used to hash |
| 731 |
the function's source code and include it in the cache key. |
| 732 |
This will only be done is source_check is True. |
| 733 |
""" |
| 734 |
|
| 735 |
# Create a tuple of (key, value) pairs, where the key is the |
| 736 |
# argument name and the value is its respective value. Order |
| 737 |
# this tuple by key. Doing this ensures the cache key created |
| 738 |
# is always the same for query string args whose keys/values |
| 739 |
# are the same, regardless of the order in which they are |
| 740 |
# provided. |
| 741 |
|
| 742 |
if query_args is None: |
| 743 |
pairs: Iterable[tuple[str, str]] = request.args.items(multi=True) |
| 744 |
else: |
| 745 |
pairs = query_args_as_pairs(query_args) |
| 746 |
|
| 747 |
args_as_sorted_tuple = tuple(sorted(pair for pair in pairs)) |
| 748 |
# ... now hash the sorted (key, value) tuple so it can be |
| 749 |
# used as a key for cache. Turn them into bytes so that the |
| 750 |
# hash function will accept them |
| 751 |
args_as_bytes = str(args_as_sorted_tuple).encode() |
| 752 |
cache_hash = self._get_hash_method(hash_method)(args_as_bytes) |
| 753 |
|
| 754 |
# Use the source code if source_check is True and update the |
| 755 |
# cache_hash before generating the hashing and using it in |
| 756 |
# cache_key |
| 757 |
if self._get_source_check(source_check) and callable(f): |
| 758 |
func_source_code = inspect.getsource(f) |
| 759 |
cache_hash.update(func_source_code.encode("utf-8")) |
| 760 |
|
| 761 |
cache_hash = str(cache_hash.hexdigest()) |
| 762 |
|
| 763 |
if callable(key_prefix): |
| 764 |
cache_key = key_prefix() |
| 765 |
elif "%s" in key_prefix: |
| 766 |
cache_key = key_prefix % (request.path if path is None else path) |
| 767 |
else: |
| 768 |
cache_key = key_prefix |
| 769 |
|
| 770 |
return cache_key + cache_hash |
| 771 |
|
| 772 |
def _make_cache_key( |
| 773 |
args: tuple[Any, ...], |
| 774 |
kwargs: dict[str, Any], |
| 775 |
use_request: bool, |
| 776 |
path: str | None = None, |
| 777 |
query_args: _QueryArgs | None = None, |
| 778 |
) -> str: |
| 779 |
if query_string: |
| 780 |
return _make_cache_key_query_string(path, query_args) |
| 781 |
else: |
| 782 |
cache_key: str |
| 783 |
if callable(key_prefix): |
| 784 |
cache_key = key_prefix() |
| 785 |
elif "%s" in key_prefix: |
| 786 |
if path is not None: |
| 787 |
cache_key = key_prefix % path |
| 788 |
elif use_request: |
| 789 |
cache_key = key_prefix % request.path |
| 790 |
else: |
| 791 |
# Outside of a request context ``url_for`` |
| 792 |
# defaults to an external URL, which would not |
| 793 |
# match the key the request stored. |
| 794 |
cache_key = key_prefix % url_for( |
| 795 |
f.__name__, _external=False, **kwargs |
| 796 |
) |
| 797 |
else: |
| 798 |
cache_key = key_prefix |
| 799 |
|
| 800 |
if self._get_source_check(source_check) and callable(f): |
| 801 |
func_source_code = inspect.getsource(f) |
| 802 |
func_source_hash = self._get_hash_method(hash_method)( |
| 803 |
func_source_code.encode("utf-8") |
| 804 |
) |
| 805 |
func_source_hash = str(func_source_hash.hexdigest()) |
| 806 |
|
| 807 |
cache_key += func_source_hash |
| 808 |
|
| 809 |
return cache_key |
| 810 |
|
| 811 |
cached_fn = cast("_CachedFunction[P, R]", decorated_function) |
| 812 |
cached_fn.uncached = f |
| 813 |
cached_fn.cache_timeout = timeout |
| 814 |
cached_fn.make_cache_key = default_make_cache_key |
| 815 |
return cached_fn |
| 816 |
|
| 817 |
return decorator |
| 818 |
|
| 819 |
def delete_cached( |
| 820 |
self, |
| 821 |
f: _AnyCachedFunction, |
| 822 |
path: str | None = None, |
| 823 |
query_args: _QueryArgs | None = None, |
| 824 |
**kwargs: Any, |
| 825 |
) -> bool: |
| 826 |
"""Delete the cached value of a :meth:`cached` decorated function. |
| 827 |
|
| 828 |
Example:: |
| 829 |
|
| 830 |
@app.route("/works") |
| 831 |
@cache.cached(query_string=True) |
| 832 |
def view_works(): |
| 833 |
return do_search(request.args) |
| 834 |
|
| 835 |
cache.delete_cached(view_works, "/works", {"limit": 15}) |
| 836 |
|
| 837 |
If you are calling this outside of a request context pass ``path`` and |
| 838 |
when the function was decorated with ``query_string=True`` you also |
| 839 |
have to pass ``query_args``. |
| 840 |
|
| 841 |
:param f: The decorated function whose cached value to delete. |
| 842 |
:param path: The ``request.path`` the value was cached for. |
| 843 |
:param query_args: The query string the value was cached for, as a |
| 844 |
query string, a mapping or an iterable of |
| 845 |
``(key, value)`` pairs. Only used when the function |
| 846 |
was decorated with ``query_string=True``. |
| 847 |
:param kwargs: The view arguments, passed to ``url_for()`` to build |
| 848 |
the path when ``path`` is not given. |
| 849 |
""" |
| 850 |
return self.delete(f.make_cache_key(path=path, query_args=query_args, **kwargs)) |
| 851 |
|
| 852 |
def _memvname(self, funcname: str) -> str: |
| 853 |
return funcname + "_memver" |
| 854 |
|
| 855 |
def _memoize_make_version_hash(self) -> str: |
| 856 |
return base64.b64encode(uuid.uuid4().bytes)[:6].decode("utf-8") |
| 857 |
|
| 858 |
def _memoize_version( |
| 859 |
self, |
| 860 |
f: Callable[..., Any], |
| 861 |
args: Any | None = None, |
| 862 |
kwargs: dict[str, Any] | None = None, |
| 863 |
reset: bool = False, |
| 864 |
delete: bool = False, |
| 865 |
refresh: bool = False, |
| 866 |
timeout: int | None = VERSION_TIMEOUT, |
| 867 |
args_to_ignore: list[str] | None = None, |
| 868 |
) -> tuple[str, str] | tuple[str, None]: |
| 869 |
"""Updates the hash version associated with a memoized function or |
| 870 |
method. |
| 871 |
""" |
| 872 |
fname, instance_fname = function_namespace(f, args=args) |
| 873 |
version_key = self._memvname(fname) |
| 874 |
fetch_keys = [version_key] |
| 875 |
|
| 876 |
args_to_ignore = args_to_ignore or [] |
| 877 |
if "self" in args_to_ignore: |
| 878 |
instance_fname = None |
| 879 |
|
| 880 |
if instance_fname: |
| 881 |
instance_version_key = self._memvname(instance_fname) |
| 882 |
fetch_keys.append(instance_version_key) |
| 883 |
|
| 884 |
# Only delete the per-instance version key or per-function version |
| 885 |
# key but not both. |
| 886 |
if delete: |
| 887 |
self.delete_many(fetch_keys[-1]) |
| 888 |
return fname, None |
| 889 |
|
| 890 |
version_data_list = list(self.get_many(*fetch_keys)) |
| 891 |
dirty = refresh |
| 892 |
|
| 893 |
if version_data_list[0] is None: |
| 894 |
version_data_list[0] = self._memoize_make_version_hash() |
| 895 |
dirty = True |
| 896 |
|
| 897 |
if instance_fname and version_data_list[1] is None: |
| 898 |
version_data_list[1] = self._memoize_make_version_hash() |
| 899 |
dirty = True |
| 900 |
|
| 901 |
# Only reset the per-instance version or the per-function version |
| 902 |
# but not both. |
| 903 |
if reset: |
| 904 |
fetch_keys = fetch_keys[-1:] |
| 905 |
version_data_list = [self._memoize_make_version_hash()] |
| 906 |
dirty = True |
| 907 |
|
| 908 |
if dirty: |
| 909 |
self.set_many( |
| 910 |
dict(zip(fetch_keys, version_data_list, strict=False)), |
| 911 |
timeout=timeout, |
| 912 |
) |
| 913 |
|
| 914 |
return fname, "".join(version_data_list) |
| 915 |
|
| 916 |
def _memoize_make_cache_key( |
| 917 |
self, |
| 918 |
make_name: Callable[..., str] | None = None, |
| 919 |
hash_method: Callable[..., Any] | None = None, |
| 920 |
source_check: bool | None = None, |
| 921 |
args_to_ignore: list[str] | None = None, |
| 922 |
) -> Callable[..., str]: |
| 923 |
"""Function used to create the cache_key for memoized functions.""" |
| 924 |
|
| 925 |
def make_cache_key(f: Callable[..., Any], *args: Any, **kwargs: Any) -> str: |
| 926 |
fname, version_data = self._memoize_version( |
| 927 |
f, |
| 928 |
args=args, |
| 929 |
kwargs=kwargs, |
| 930 |
args_to_ignore=args_to_ignore, |
| 931 |
) |
| 932 |
|
| 933 |
#: this should have to be after version_data, so that it |
| 934 |
#: does not break the delete_memoized functionality. |
| 935 |
altfname = make_name(fname) if callable(make_name) else fname |
| 936 |
|
| 937 |
if callable(f): |
| 938 |
keyargs, keykwargs = self._memoize_kwargs_to_args( |
| 939 |
f, *args, **kwargs, args_to_ignore=args_to_ignore |
| 940 |
) |
| 941 |
else: |
| 942 |
keyargs, keykwargs = args, kwargs |
| 943 |
|
| 944 |
updated = f"{altfname}{keyargs}{keykwargs}" |
| 945 |
|
| 946 |
cache_hash = self._get_hash_method(hash_method)() |
| 947 |
cache_hash.update(updated.encode("utf-8")) |
| 948 |
|
| 949 |
# Use the source code if source_check is True and update the |
| 950 |
# cache_key with the function's source. |
| 951 |
if self._get_source_check(source_check) and callable(f): |
| 952 |
func_source_code = inspect.getsource(f) |
| 953 |
cache_hash.update(func_source_code.encode("utf-8")) |
| 954 |
|
| 955 |
cache_key = base64.b64encode(cache_hash.digest())[:16].decode("utf-8") |
| 956 |
cache_key += version_data or "" |
| 957 |
|
| 958 |
return cache_key |
| 959 |
|
| 960 |
return make_cache_key |
| 961 |
|
| 962 |
def _memoize_kwargs_to_args( |
| 963 |
self, f: Callable[..., Any], *args: Any, **kwargs: Any |
| 964 |
) -> Any: |
| 965 |
#: Inspect the arguments to the function |
| 966 |
#: This allows the memoization to be the same |
| 967 |
#: whether the function was called with |
| 968 |
#: 1, b=2 is equivalent to a=1, b=2, etc. |
| 969 |
new_args = [] |
| 970 |
arg_num = 0 |
| 971 |
args_to_ignore = kwargs.pop("args_to_ignore", None) or [] |
| 972 |
|
| 973 |
# If the function uses VAR_KEYWORD type of parameters, |
| 974 |
# we need to pass these further |
| 975 |
kw_keys_remaining = [key for key in kwargs if key not in args_to_ignore] |
| 976 |
arg_names = get_arg_names(f) |
| 977 |
args_len = len(arg_names) |
| 978 |
|
| 979 |
for i in range(args_len): |
| 980 |
arg_default = get_arg_default(f, i) |
| 981 |
if arg_names[i] in args_to_ignore: |
| 982 |
arg = None |
| 983 |
arg_num += 1 |
| 984 |
elif i == 0 and arg_names[i] in ("self", "cls"): |
| 985 |
#: use the id func of the class instance |
| 986 |
#: this supports instance methods for |
| 987 |
#: the memoized functions, giving more |
| 988 |
#: flexibility to developers |
| 989 |
if not args: |
| 990 |
raise ValueError( |
| 991 |
"When using `delete_memoized` on a " |
| 992 |
f"`{'classmethod' if arg_names[i] == 'cls' else 'method'}` " |
| 993 |
f"you must provide the `{arg_names[i]}` argument " |
| 994 |
"as the first positional argument." |
| 995 |
) |
| 996 |
arg = get_id(args[0]) |
| 997 |
arg_num += 1 |
| 998 |
elif arg_names[i] in kwargs: |
| 999 |
arg = kwargs[arg_names[i]] |
| 1000 |
kw_keys_remaining.pop(kw_keys_remaining.index(arg_names[i])) |
| 1001 |
elif arg_num < len(args): |
| 1002 |
arg = args[arg_num] |
| 1003 |
arg_num += 1 |
| 1004 |
elif arg_default is not None: |
| 1005 |
arg = arg_default |
| 1006 |
arg_num += 1 |
| 1007 |
else: |
| 1008 |
arg = None |
| 1009 |
arg_num += 1 |
| 1010 |
|
| 1011 |
#: Attempt to convert all arguments to a |
| 1012 |
#: hash/id or a representation? |
| 1013 |
#: Not sure if this is necessary, since |
| 1014 |
#: using objects as keys gets tricky quickly. |
| 1015 |
# if hasattr(arg, '__class__'): |
| 1016 |
# try: |
| 1017 |
# arg = hash(arg) |
| 1018 |
# except: |
| 1019 |
# arg = get_id(arg) |
| 1020 |
|
| 1021 |
#: Or what about a special __cacherepr__ function |
| 1022 |
#: on an object, this allows objects to act normal |
| 1023 |
#: upon inspection, yet they can define a representation |
| 1024 |
#: that can be used to make the object unique in the |
| 1025 |
#: cache key. Given that a case comes across that |
| 1026 |
#: an object "must" be used as a cache key |
| 1027 |
# if hasattr(arg, '__cacherepr__'): |
| 1028 |
# arg = arg.__cacherepr__ |
| 1029 |
|
| 1030 |
new_args.append(arg) |
| 1031 |
|
| 1032 |
new_args.extend(args[len(arg_names) :]) |
| 1033 |
return ( |
| 1034 |
tuple(new_args), |
| 1035 |
OrderedDict( |
| 1036 |
sorted((k, v) for k, v in kwargs.items() if k in kw_keys_remaining) |
| 1037 |
), |
| 1038 |
) |
| 1039 |
|
| 1040 |
def _bypass_cache( |
| 1041 |
self, |
| 1042 |
unless: Callable[..., Any] | None, |
| 1043 |
f: Callable[..., Any], |
| 1044 |
*args: Any, |
| 1045 |
**kwargs: Any, |
| 1046 |
) -> bool: |
| 1047 |
"""Determines whether or not to bypass the cache by calling unless(). |
| 1048 |
Supports both unless() that takes in arguments and unless() |
| 1049 |
that doesn't. |
| 1050 |
""" |
| 1051 |
bypass_cache = False |
| 1052 |
|
| 1053 |
if callable(unless): |
| 1054 |
# If unless() takes args, pass them in. |
| 1055 |
if wants_args(unless): |
| 1056 |
if unless(f, *args, **kwargs) is True: |
| 1057 |
bypass_cache = True |
| 1058 |
elif unless() is True: |
| 1059 |
bypass_cache = True |
| 1060 |
|
| 1061 |
return bypass_cache |
| 1062 |
|
| 1063 |
def _forced_update( |
| 1064 |
self, |
| 1065 |
forced_update: Callable[..., Any] | None, |
| 1066 |
*args: Any, |
| 1067 |
**kwargs: Any, |
| 1068 |
) -> bool: |
| 1069 |
if not callable(forced_update): |
| 1070 |
return False |
| 1071 |
|
| 1072 |
# If forced_update() takes args, pass them in. |
| 1073 |
if wants_args(forced_update): |
| 1074 |
return forced_update(*args, **kwargs) is True |
| 1075 |
|
| 1076 |
return forced_update() is True |
| 1077 |
|
| 1078 |
def _is_stale( |
| 1079 |
self, |
| 1080 |
is_stale: Callable[..., Any] | None, |
| 1081 |
rv: Any, |
| 1082 |
*args: Any, |
| 1083 |
**kwargs: Any, |
| 1084 |
) -> bool: |
| 1085 |
if not callable(is_stale): |
| 1086 |
return False |
| 1087 |
|
| 1088 |
# If is_stale() takes args besides the cached value, pass them in. |
| 1089 |
if wants_extra_args(is_stale): |
| 1090 |
return is_stale(rv, *args, **kwargs) is True |
| 1091 |
|
| 1092 |
return is_stale(rv) is True |
| 1093 |
|
| 1094 |
def memoize( |
| 1095 |
self, |
| 1096 |
timeout: _Timeout | None = None, |
| 1097 |
make_name: Callable[..., str] | None = None, |
| 1098 |
unless: Callable[..., bool] | None = None, |
| 1099 |
forced_update: Callable[..., bool] | None = None, |
| 1100 |
is_stale: Callable[..., bool] | None = None, |
| 1101 |
response_filter: Callable[..., Any] | None = None, |
| 1102 |
hash_method: Callable[..., Any] | None = None, |
| 1103 |
cache_none: bool = False, |
| 1104 |
source_check: bool | None = None, |
| 1105 |
args_to_ignore: list[str] | None = None, |
| 1106 |
) -> Callable[[Callable[P, R]], _MemoizedFunction[P, R]]: |
| 1107 |
"""Use this to cache the result of a function, taking its arguments |
| 1108 |
into account in the cache key. |
| 1109 |
|
| 1110 |
Information on |
| 1111 |
`Memoization <http://en.wikipedia.org/wiki/Memoization>`_. |
| 1112 |
|
| 1113 |
Example:: |
| 1114 |
|
| 1115 |
@cache.memoize(timeout=50) |
| 1116 |
def big_foo(a, b): |
| 1117 |
return a + b + random.randrange(0, 1000) |
| 1118 |
|
| 1119 |
.. code-block:: pycon |
| 1120 |
|
| 1121 |
>>> big_foo(5, 2) |
| 1122 |
753 |
| 1123 |
>>> big_foo(5, 3) |
| 1124 |
234 |
| 1125 |
>>> big_foo(5, 2) |
| 1126 |
753 |
| 1127 |
|
| 1128 |
.. versionadded:: 0.4 |
| 1129 |
The returned decorated function now has three function attributes |
| 1130 |
assigned to it. |
| 1131 |
|
| 1132 |
**uncached** |
| 1133 |
The original undecorated function. readable only |
| 1134 |
|
| 1135 |
**cache_timeout** |
| 1136 |
The cache timeout value for this function. |
| 1137 |
For a custom value to take affect, this must be |
| 1138 |
set before the function is called. |
| 1139 |
|
| 1140 |
readable and writable |
| 1141 |
|
| 1142 |
**make_cache_key** |
| 1143 |
A function used in generating the cache_key used. |
| 1144 |
|
| 1145 |
readable and writable |
| 1146 |
|
| 1147 |
|
| 1148 |
:param timeout: Default None. If set to an integer, will cache for that |
| 1149 |
amount of time. Unit of time is in seconds. A |
| 1150 |
``datetime.timedelta`` is also accepted and is rounded |
| 1151 |
up to whole seconds. |
| 1152 |
|
| 1153 |
:param make_name: Default None. If set this is a function that accepts |
| 1154 |
a single argument, the function name, and returns a |
| 1155 |
new string to be used as the function name. |
| 1156 |
If not set then the function name is used. |
| 1157 |
|
| 1158 |
:param unless: Default None. Cache will *always* execute the caching |
| 1159 |
facilities unless this callable is true. |
| 1160 |
This will bypass the caching entirely. |
| 1161 |
|
| 1162 |
:param forced_update: Default None. If this callable is true, |
| 1163 |
cache value will be updated regardless cache |
| 1164 |
is expired or not. Useful for background |
| 1165 |
renewal of cached functions. |
| 1166 |
|
| 1167 |
:param is_stale: Default None. Called on a cache hit with the cached |
| 1168 |
value as its first argument. If it is true the cached |
| 1169 |
value will be recomputed. If the callable accepts more |
| 1170 |
than one argument, the calls own arguments are passed |
| 1171 |
after the cached value. |
| 1172 |
|
| 1173 |
:param response_filter: Default None. If not None, the callable is |
| 1174 |
invoked after the cached funtion evaluation, |
| 1175 |
and is given one arguement, the response |
| 1176 |
content. If the callable returns False, the |
| 1177 |
content will not be cached. Useful to prevent |
| 1178 |
caching of code 500 responses. |
| 1179 |
:param hash_method: Default None. If ``None``, the value is set by |
| 1180 |
``CACHE_HASH_METHOD``, which itself defaults to |
| 1181 |
``hashlib.sha256``. The hash method used to |
| 1182 |
generate the keys for cached results. |
| 1183 |
|
| 1184 |
:param cache_none: Default False. If set to True, add a key exists |
| 1185 |
check when cache.get returns None. This will likely |
| 1186 |
lead to wrongly returned None values in concurrent |
| 1187 |
situations and is not recommended to use. |
| 1188 |
|
| 1189 |
:param source_check: Default None. If None will use the value set by |
| 1190 |
CACHE_SOURCE_CHECK. |
| 1191 |
If True, include the function's source code in the |
| 1192 |
hash to avoid using cached values when the source |
| 1193 |
code has changed and the input values remain the |
| 1194 |
same. This ensures that the cache_key will be |
| 1195 |
formed with the function's source code hash in |
| 1196 |
addition to other parameters that may be included |
| 1197 |
in the formation of the key. |
| 1198 |
|
| 1199 |
:param args_to_ignore: List of arguments that will be ignored while |
| 1200 |
generating the cache key. Default to None. |
| 1201 |
This means that those arguments may change |
| 1202 |
without affecting the cache value that will be |
| 1203 |
returned. |
| 1204 |
|
| 1205 |
.. versionadded:: 0.5 |
| 1206 |
params ``make_name``, ``unless`` |
| 1207 |
|
| 1208 |
.. versionadded:: 1.10 |
| 1209 |
params ``args_to_ignore`` |
| 1210 |
""" |
| 1211 |
|
| 1212 |
def memoize(f: Callable[P, R]) -> _MemoizedFunction[P, R]: |
| 1213 |
@functools.wraps(f) |
| 1214 |
def decorated_function(*args: Any, **kwargs: Any) -> Any: |
| 1215 |
#: bypass cache |
| 1216 |
if self._bypass_cache(unless, f, *args, **kwargs): |
| 1217 |
return self._call_fn(f, *args, **kwargs) |
| 1218 |
|
| 1219 |
try: |
| 1220 |
forced_update_result = self._forced_update( |
| 1221 |
forced_update, *args, **kwargs |
| 1222 |
) |
| 1223 |
|
| 1224 |
cache_key = self._memoize_make_cache_key( |
| 1225 |
make_name=make_name, |
| 1226 |
hash_method=hash_method, |
| 1227 |
source_check=source_check, |
| 1228 |
args_to_ignore=args_to_ignore, |
| 1229 |
)(f, *args, **kwargs) |
| 1230 |
|
| 1231 |
if forced_update_result: |
| 1232 |
rv = None |
| 1233 |
found = False |
| 1234 |
else: |
| 1235 |
rv = self.get(cache_key) |
| 1236 |
found = True |
| 1237 |
|
| 1238 |
# If the value returned by cache.get() is None, it |
| 1239 |
# might be because the key is not found in the cache |
| 1240 |
# or because the cached value is actually None |
| 1241 |
if rv is None: |
| 1242 |
# If we're sure we don't need to cache None values |
| 1243 |
# (cache_none=False), don't bother checking for |
| 1244 |
# key existence, as it can lead to false positives |
| 1245 |
# if a concurrent call already cached the |
| 1246 |
# key between steps. This would cause us to |
| 1247 |
# return None when we shouldn't |
| 1248 |
if not cache_none: |
| 1249 |
found = False |
| 1250 |
else: |
| 1251 |
found = self.has(cache_key) |
| 1252 |
|
| 1253 |
if found and self._is_stale(is_stale, rv, *args, **kwargs): |
| 1254 |
rv = None |
| 1255 |
found = False |
| 1256 |
except Exception: |
| 1257 |
if self.app.debug: |
| 1258 |
raise |
| 1259 |
logger.exception("Exception possibly due to cache backend.") |
| 1260 |
return self._call_fn(f, *args, **kwargs) |
| 1261 |
|
| 1262 |
if self.enable_signals: |
| 1263 |
signal = cache_memoize_hit if found else cache_memoize_miss |
| 1264 |
signal.send( |
| 1265 |
cache=self, cache_key=cache_key, f=f, args=args, kwargs=kwargs |
| 1266 |
) |
| 1267 |
|
| 1268 |
if not found: |
| 1269 |
rv = self._call_fn(f, *args, **kwargs) |
| 1270 |
if inspect.isgenerator(rv): |
| 1271 |
rv = join_generator(rv) |
| 1272 |
|
| 1273 |
if response_filter is None or response_filter(rv): |
| 1274 |
cache_timeout = normalize_timeout(memoized_fn.cache_timeout) |
| 1275 |
|
| 1276 |
try: |
| 1277 |
self.set( |
| 1278 |
cache_key, |
| 1279 |
rv, |
| 1280 |
timeout=cache_timeout, |
| 1281 |
) |
| 1282 |
# update the memoize version with the new cache_timeout |
| 1283 |
self._memoize_version( |
| 1284 |
f, |
| 1285 |
args=args, |
| 1286 |
kwargs=kwargs, |
| 1287 |
refresh=True, |
| 1288 |
timeout=cache_timeout, |
| 1289 |
args_to_ignore=args_to_ignore, |
| 1290 |
) |
| 1291 |
except Exception: |
| 1292 |
if self.app.debug: |
| 1293 |
raise |
| 1294 |
logger.exception("Exception possibly due to cache backend.") |
| 1295 |
return rv |
| 1296 |
|
| 1297 |
memoized_fn = cast("_MemoizedFunction[P, R]", decorated_function) |
| 1298 |
memoized_fn.uncached = f |
| 1299 |
memoized_fn.cache_timeout = timeout |
| 1300 |
memoized_fn.make_cache_key = self._memoize_make_cache_key( |
| 1301 |
make_name=make_name, |
| 1302 |
hash_method=hash_method, |
| 1303 |
source_check=source_check, |
| 1304 |
args_to_ignore=args_to_ignore, |
| 1305 |
) |
| 1306 |
# Equivalent to passing ``f``: ``function_namespace`` reads only |
| 1307 |
# dunders copied by ``functools.wraps`` and a signature that |
| 1308 |
# follows ``__wrapped__``. |
| 1309 |
memoized_fn.delete_memoized = lambda: self.delete_memoized(memoized_fn) |
| 1310 |
return memoized_fn |
| 1311 |
|
| 1312 |
return memoize |
| 1313 |
|
| 1314 |
def delete_memoized( |
| 1315 |
self, f: _AnyMemoizedFunction, *args: Any, **kwargs: Any |
| 1316 |
) -> None: |
| 1317 |
"""Deletes the specified functions caches, based by given parameters. |
| 1318 |
If parameters are given, only the functions that were memoized |
| 1319 |
with them will be erased. Otherwise all versions of the caches |
| 1320 |
will be forgotten. |
| 1321 |
|
| 1322 |
Example:: |
| 1323 |
|
| 1324 |
@cache.memoize(50) |
| 1325 |
def random_func(): |
| 1326 |
return random.randrange(1, 50) |
| 1327 |
|
| 1328 |
@cache.memoize() |
| 1329 |
def param_func(a, b): |
| 1330 |
return a+b+random.randrange(1, 50) |
| 1331 |
|
| 1332 |
.. code-block:: pycon |
| 1333 |
|
| 1334 |
>>> random_func() |
| 1335 |
43 |
| 1336 |
>>> random_func() |
| 1337 |
43 |
| 1338 |
>>> cache.delete_memoized(random_func) |
| 1339 |
>>> random_func() |
| 1340 |
16 |
| 1341 |
>>> param_func(1, 2) |
| 1342 |
32 |
| 1343 |
>>> param_func(1, 2) |
| 1344 |
32 |
| 1345 |
>>> param_func(2, 2) |
| 1346 |
47 |
| 1347 |
>>> cache.delete_memoized(param_func, 1, 2) |
| 1348 |
>>> param_func(1, 2) |
| 1349 |
13 |
| 1350 |
>>> param_func(2, 2) |
| 1351 |
47 |
| 1352 |
|
| 1353 |
Delete memoized is also smart about instance methods vs class methods. |
| 1354 |
|
| 1355 |
When passing a instancemethod, it will only clear the cache related |
| 1356 |
to that instance of that object. (object uniqueness can be overridden |
| 1357 |
by defining the __repr__ method, such as user id). |
| 1358 |
|
| 1359 |
When passing a classmethod, it will clear all caches related across |
| 1360 |
all instances of that class. |
| 1361 |
|
| 1362 |
Example:: |
| 1363 |
|
| 1364 |
class Adder(object): |
| 1365 |
@cache.memoize() |
| 1366 |
def add(self, b): |
| 1367 |
return b + random.random() |
| 1368 |
|
| 1369 |
.. code-block:: pycon |
| 1370 |
|
| 1371 |
>>> adder1 = Adder() |
| 1372 |
>>> adder2 = Adder() |
| 1373 |
>>> adder1.add(3) |
| 1374 |
3.23214234 |
| 1375 |
>>> adder2.add(3) |
| 1376 |
3.60898509 |
| 1377 |
>>> cache.delete_memoized(adder1.add) |
| 1378 |
>>> adder1.add(3) |
| 1379 |
3.01348673 |
| 1380 |
>>> adder2.add(3) |
| 1381 |
3.60898509 |
| 1382 |
>>> cache.delete_memoized(Adder.add) |
| 1383 |
>>> adder1.add(3) |
| 1384 |
3.53235667 |
| 1385 |
>>> adder2.add(3) |
| 1386 |
3.72341788 |
| 1387 |
|
| 1388 |
Arguments narrow the deletion down to a single call. A bound method |
| 1389 |
supplies its own instance, so only the remaining arguments are given: |
| 1390 |
|
| 1391 |
.. code-block:: pycon |
| 1392 |
|
| 1393 |
>>> cache.delete_memoized(adder1.add, 3) |
| 1394 |
|
| 1395 |
When the function is reached through the class instead, the instance |
| 1396 |
has to be passed explicitly, the same way a class is passed for a |
| 1397 |
``@classmethod``: |
| 1398 |
|
| 1399 |
.. code-block:: pycon |
| 1400 |
|
| 1401 |
>>> cache.delete_memoized(Adder.add, adder1, 3) |
| 1402 |
|
| 1403 |
.. versionchanged:: 2.5.0 |
| 1404 |
|
| 1405 |
A bound method no longer needs to be given its own instance as the |
| 1406 |
first argument. Passing it explicitly keeps working. |
| 1407 |
|
| 1408 |
:param fname: The memoized function. |
| 1409 |
:param \\*args: A list of positional parameters used with |
| 1410 |
memoized function. |
| 1411 |
:param \\**kwargs: A dict of named parameters used with |
| 1412 |
memoized function. |
| 1413 |
|
| 1414 |
.. note:: |
| 1415 |
|
| 1416 |
Flask-Caching uses inspect to order kwargs into positional args when |
| 1417 |
the function is memoized. If you pass a function reference into |
| 1418 |
``fname``, Flask-Caching will be able to place the args/kwargs in |
| 1419 |
the proper order, and delete the positional cache. |
| 1420 |
|
| 1421 |
However, if ``delete_memoized`` is just called with the name of the |
| 1422 |
function, be sure to pass in potential arguments in the same order |
| 1423 |
as defined in your function as args only, otherwise Flask-Caching |
| 1424 |
will not be able to compute the same cache key and delete all |
| 1425 |
memoized versions of it. |
| 1426 |
|
| 1427 |
.. note:: |
| 1428 |
|
| 1429 |
Flask-Caching maintains an internal random version hash for |
| 1430 |
the function. Using delete_memoized will only swap out |
| 1431 |
the version hash, causing the memoize function to recompute |
| 1432 |
results and put them into another key. |
| 1433 |
|
| 1434 |
This leaves any computed caches for this memoized function within |
| 1435 |
the caching backend. |
| 1436 |
|
| 1437 |
It is recommended to use a very high timeout with memoize if using |
| 1438 |
this function, so that when the version hash is swapped, the old |
| 1439 |
cached results would eventually be reclaimed by the caching |
| 1440 |
backend. |
| 1441 |
""" |
| 1442 |
if not callable(f): |
| 1443 |
raise TypeError( |
| 1444 |
"Deleting messages by relative name is not supported, please " |
| 1445 |
"use a function reference." |
| 1446 |
) |
| 1447 |
|
| 1448 |
if not (args or kwargs): |
| 1449 |
self._memoize_version(f, reset=True) |
| 1450 |
else: |
| 1451 |
args = self._ensure_self_arg(f, args) |
| 1452 |
cache_key = f.make_cache_key(f.uncached, *args, **kwargs) |
| 1453 |
self.delete(cache_key) |
| 1454 |
|
| 1455 |
@staticmethod |
| 1456 |
def _ensure_self_arg( |
| 1457 |
f: _AnyMemoizedFunction, args: tuple[Any, ...] |
| 1458 |
) -> tuple[Any, ...]: |
| 1459 |
"""Supply the ``self`` argument when a bound method is passed. |
| 1460 |
|
| 1461 |
``make_cache_key`` works on the undecorated function, so the instance |
| 1462 |
has to be part of ``args`` to compute the same key that was used when |
| 1463 |
the value was cached. A bound method already carries it, so passing it |
| 1464 |
again is redundant:: |
| 1465 |
|
| 1466 |
cache.delete_memoized(adder.add, 3) |
| 1467 |
|
| 1468 |
Passing it explicitly keeps working, so that the form previously |
| 1469 |
required for instance methods is not broken. |
| 1470 |
""" |
| 1471 |
instance = getattr(f, "__self__", None) |
| 1472 |
|
| 1473 |
if instance is None or inspect.isclass(instance): |
| 1474 |
return args |
| 1475 |
|
| 1476 |
arg_names = get_arg_names(f.uncached) |
| 1477 |
|
| 1478 |
if not arg_names or arg_names[0] != "self" or (args and args[0] is instance): |
| 1479 |
return args |
| 1480 |
|
| 1481 |
return (instance, *args) |
| 1482 |
|
| 1483 |
def delete_memoized_verhash(self, f: _AnyMemoizedFunction, *args: Any) -> None: |
| 1484 |
"""Delete the version hash associated with the function. |
| 1485 |
|
| 1486 |
.. warning:: |
| 1487 |
|
| 1488 |
Performing this operation could leave keys behind that have |
| 1489 |
been created with this version hash. It is up to the application |
| 1490 |
to make sure that all keys that may have been created with this |
| 1491 |
version hash at least have timeouts so they will not sit orphaned |
| 1492 |
in the cache backend. |
| 1493 |
""" |
| 1494 |
if not callable(f): |
| 1495 |
raise TypeError( |
| 1496 |
"Deleting messages by relative name is not supported, please" |
| 1497 |
"use a function reference." |
| 1498 |
) |
| 1499 |
|
| 1500 |
self._memoize_version(f, delete=True) |
| 1501 |
|
| 1502 |
|
| 1503 |
def __getattr__(name: str) -> Any: |
| 1504 |
if name == "__version__": |
| 1505 |
import importlib.metadata |
| 1506 |
|
| 1507 |
warnings.warn( |
| 1508 |
"The '__version__' attribute is deprecated and will be removed in" |
| 1509 |
" Flask-Caching 3.0. Use feature detection or" |
| 1510 |
" 'importlib.metadata.version(\"flask-caching\")' instead.", |
| 1511 |
DeprecationWarning, |
| 1512 |
stacklevel=2, |
| 1513 |
) |
| 1514 |
return importlib.metadata.version("flask-caching") |
| 1515 |
|
| 1516 |
raise AttributeError(name) |