Debian Codegraph @

src/flask_caching/__init__.py

raw
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 typing import Any
21 from typing import Union
22
23 from flask import current_app
24 from flask import Flask
25 from flask import g
26 from flask import request
27 from flask import Response
28 from flask import url_for
29 from werkzeug.utils import import_string
30
31 from flask_caching.backends.base import BaseCache
32 from flask_caching.backends.simplecache import SimpleCache
33 from flask_caching.utils import function_namespace
34 from flask_caching.utils import get_arg_default
35 from flask_caching.utils import get_arg_names
36 from flask_caching.utils import get_id
37 from flask_caching.utils import make_template_fragment_key # noqa: F401
38 from flask_caching.utils import wants_args
39
40 __version__ = "2.4.1"
41
42 logger = logging.getLogger(__name__)
43
44 SUPPORTED_HASH_FUNCTIONS = [
45 hashlib.sha1,
46 hashlib.sha224,
47 hashlib.sha256,
48 hashlib.sha384,
49 hashlib.sha512,
50 hashlib.md5,
51 ]
52
53
54 class CachedResponse(Response):
55 """
56 views wraped by @cached can return this (which inherits from flask.Response)
57 to override the cache TTL dynamically
58 """
59
60 timeout: int | None = None
61
62 def __init__(self, response: Response, timeout: int | None) -> None:
63 # ``CachedResponse`` adopts the state of an existing Response in
64 # place rather than calling ``Response.__init__``; copying
65 # ``__dict__`` preserves headers, status and body without having
66 # to round-trip the response through Werkzeug's constructor.
67 self.__dict__ = response.__dict__
68 self.timeout = timeout
69
70
71 class Cache:
72 """This class is used to control the cache objects."""
73
74 def __init__(
75 self,
76 app: Flask | None = None,
77 with_jinja2_ext: bool = True,
78 config=None,
79 ) -> None:
80 if not (config is None or isinstance(config, dict)):
81 raise ValueError("`config` must be an instance of dict or None")
82
83 self.with_jinja2_ext = with_jinja2_ext
84 self.config = config
85
86 self.source_check = None
87
88 if app is not None:
89 self.init_app(app, config)
90
91 def init_app(self, app: Flask, config=None) -> None:
92 """This is used to initialize cache with your app object"""
93 if not (config is None or isinstance(config, dict)):
94 raise ValueError("`config` must be an instance of dict or None")
95
96 #: Ref PR #44.
97 #: Do not set self.app in the case a single instance of the Cache
98 #: object is being used for multiple app instances.
99 #: Example use case would be Cache shipped as part of a blueprint
100 #: or utility library.
101
102 base_config = app.config.copy()
103 if self.config:
104 base_config.update(self.config)
105 if config:
106 base_config.update(config)
107 config = base_config
108
109 config.setdefault("CACHE_DEFAULT_TIMEOUT", 300)
110 config.setdefault("CACHE_IGNORE_ERRORS", False)
111 config.setdefault("CACHE_THRESHOLD", 500)
112 config.setdefault("CACHE_KEY_PREFIX", "flask_cache_")
113 config.setdefault("CACHE_MEMCACHED_SERVERS", None)
114 config.setdefault("CACHE_DIR", None)
115 config.setdefault("CACHE_OPTIONS", None)
116 config.setdefault("CACHE_ARGS", [])
117 config.setdefault("CACHE_TYPE", "null")
118 config.setdefault("CACHE_NO_NULL_WARNING", False)
119 config.setdefault("CACHE_SOURCE_CHECK", False)
120
121 if config["CACHE_TYPE"] == "null" and not config["CACHE_NO_NULL_WARNING"]:
122 warnings.warn(
123 "Flask-Caching: CACHE_TYPE is set to null, "
124 "caching is effectively disabled.",
125 stacklevel=2,
126 )
127
128 if (
129 config["CACHE_TYPE"] in ["filesystem", "FileSystemCache"]
130 and config["CACHE_DIR"] is None
131 ):
132 warnings.warn(
133 f"Flask-Caching: CACHE_TYPE is set to {config['CACHE_TYPE']} but no "
134 "CACHE_DIR is set.",
135 stacklevel=2,
136 )
137
138 self.source_check = config["CACHE_SOURCE_CHECK"]
139
140 if self.with_jinja2_ext:
141 from .jinja2ext import CacheExtension
142 from .jinja2ext import JINJA_CACHE_ATTR_NAME
143
144 setattr(app.jinja_env, JINJA_CACHE_ATTR_NAME, self)
145 app.jinja_env.add_extension(CacheExtension)
146
147 self._set_cache(app, config)
148
149 def _set_cache(self, app: Flask, config) -> None:
150 import_me = config["CACHE_TYPE"]
151 if "." not in import_me:
152 plain_name_used = True
153 import_me = "flask_caching.backends." + import_me
154 else:
155 plain_name_used = False
156
157 cache_factory = import_string(import_me)
158 cache_args = config["CACHE_ARGS"][:]
159 cache_options = {"default_timeout": config["CACHE_DEFAULT_TIMEOUT"]}
160
161 if isinstance(cache_factory, type) and issubclass(cache_factory, BaseCache):
162 cache_factory = cache_factory.factory
163 elif plain_name_used:
164 warnings.warn(
165 "Using the initialization functions in flask_caching.backend "
166 "is deprecated. Use the a full path to backend classes "
167 "directly.",
168 category=DeprecationWarning,
169 stacklevel=2,
170 )
171
172 if config["CACHE_OPTIONS"]:
173 cache_options.update(config["CACHE_OPTIONS"])
174
175 if not hasattr(app, "extensions"):
176 app.extensions = {}
177
178 app.extensions.setdefault("cache", {})
179 app.extensions["cache"][self] = cache_factory(
180 app, config, cache_args, cache_options
181 )
182 self.app = app
183
184 def _call_fn(self, fn, *args, **kwargs):
185 ensure_sync = getattr(self.app, "ensure_sync", None)
186 if ensure_sync is not None:
187 return ensure_sync(fn)(*args, **kwargs)
188 return fn(*args, **kwargs)
189
190 @property
191 def cache(self) -> SimpleCache:
192 app = current_app or self.app
193 return app.extensions["cache"][self]
194
195 def get(self, *args, **kwargs) -> Any:
196 """Proxy function for internal cache object."""
197 return self.cache.get(*args, **kwargs)
198
199 def has(self, *args, **kwargs) -> bool:
200 """Proxy function for internal cache object."""
201 return self.cache.has(*args, **kwargs)
202
203 def set(self, *args, **kwargs) -> bool | None:
204 """Proxy function for internal cache object."""
205 return self.cache.set(*args, **kwargs)
206
207 def add(self, *args, **kwargs) -> bool:
208 """Proxy function for internal cache object."""
209 return self.cache.add(*args, **kwargs)
210
211 def delete(self, *args, **kwargs) -> bool:
212 """Proxy function for internal cache object."""
213 return self.cache.delete(*args, **kwargs)
214
215 def delete_many(self, *args, **kwargs) -> list[str]:
216 """Proxy function for internal cache object."""
217 return self.cache.delete_many(*args, **kwargs)
218
219 def clear(self) -> bool:
220 """Proxy function for internal cache object."""
221 return self.cache.clear()
222
223 def get_many(self, *args, **kwargs):
224 """Proxy function for internal cache object."""
225 return self.cache.get_many(*args, **kwargs)
226
227 def set_many(self, *args, **kwargs) -> list[Any]:
228 """Proxy function for internal cache object."""
229 return self.cache.set_many(*args, **kwargs)
230
231 def get_dict(self, *args, **kwargs) -> dict[str, Any]:
232 """Proxy function for internal cache object."""
233 return self.cache.get_dict(*args, **kwargs)
234
235 def unlink(self, *args, **kwargs) -> list[str]:
236 """Proxy function for internal cache object
237 only support Redis
238 """
239 unlink = getattr(self.cache, "unlink", None)
240 if unlink is not None and callable(unlink):
241 return unlink(*args, **kwargs)
242 return self.delete_many(*args, **kwargs)
243
244 def cached(
245 self,
246 timeout: int | None = None,
247 key_prefix: str = "view/%s",
248 unless: Callable | None = None,
249 forced_update: Callable | None = None,
250 response_filter: Callable | None = None,
251 query_string: bool = False,
252 hash_method: Callable = hashlib.md5,
253 cache_none: bool = False,
254 make_cache_key: Callable | None = None,
255 source_check: bool | None = None,
256 response_hit_indication: bool | None = False,
257 ) -> Callable:
258 """Decorator. Use this to cache a function. By default the cache key
259 is `view/request.path`. You are able to use this decorator with any
260 function by changing the `key_prefix`. If the token `%s` is located
261 within the `key_prefix` then it will replace that with `request.path`
262
263 Example::
264
265 # An example view function
266 @cache.cached(timeout=50)
267 def big_foo():
268 return big_bar_calc()
269
270 # An example misc function to cache.
271 @cache.cached(key_prefix='MyCachedList')
272 def get_list():
273 return [random.randrange(0, 1) for i in range(50000)]
274
275 my_list = get_list()
276
277 .. note::
278
279 You MUST have a request context to actually called any functions
280 that are cached.
281
282 .. versionadded:: 0.4
283 The returned decorated function now has three function attributes
284 assigned to it. These attributes are readable/writable.
285
286 **uncached**
287 The original undecorated function
288
289 **cache_timeout**
290 The cache timeout value for this function. For a
291 custom value to take affect, this must be set before the
292 function is called.
293
294 **make_cache_key**
295 A function used in generating the cache_key used.
296
297 readable and writable
298
299 :param timeout: Default None. If set to an integer, will cache for that
300 amount of time. Unit of time is in seconds.
301
302 :param key_prefix: Default 'view/%(request.path)s'. Beginning key to .
303 use for the cache key. `request.path` will be the
304 actual request path, or in cases where the
305 `make_cache_key`-function is called from other
306 views it will be the expected URL for the view
307 as generated by Flask's `url_for()`.
308
309 .. versionadded:: 0.3.4
310 Can optionally be a callable which takes
311 no arguments but returns a string that will
312 be used as the cache_key.
313
314 :param unless: Default None. Cache will *always* execute the caching
315 facilities unless this callable is true.
316 This will bypass the caching entirely.
317
318 :param forced_update: Default None. If this callable is true,
319 cache value will be updated regardless cache
320 is expired or not. Useful for background
321 renewal of cached functions.
322
323 :param response_filter: Default None. If not None, the callable is
324 invoked after the cached function evaluation,
325 and is given one argument, the response
326 content. If the callable returns False, the
327 content will not be cached. Useful to prevent
328 caching of code 500 responses.
329
330 :param query_string: Default False. When True, the cache key
331 used will be the result of hashing the
332 ordered query string parameters. This
333 avoids creating different caches for
334 the same query just because the parameters
335 were passed in a different order. See
336 _make_cache_key_query_string() for more
337 details.
338
339 :param hash_method: Default hashlib.md5. The hash method used to
340 generate the keys for cached results.
341 :param cache_none: Default False. If set to True, add a key exists
342 check when cache.get returns None. This will likely
343 lead to wrongly returned None values in concurrent
344 situations and is not recommended to use.
345 :param make_cache_key: Default None. If set to a callable object,
346 it will be called to generate the cache key
347
348 :param source_check: Default None. If None will use the value set by
349 CACHE_SOURCE_CHECK.
350 If True, include the function's source code in the
351 hash to avoid using cached values when the source
352 code has changed and the input values remain the
353 same. This ensures that the cache_key will be
354 formed with the function's source code hash in
355 addition to other parameters that may be included
356 in the formation of the key.
357
358 :param response_hit_indication: Default False.
359 If True, it will add to response header field 'hit_cache'
360 if used cache.
361 """
362
363 def decorator(f):
364 @functools.wraps(f)
365 def decorated_function(*args, **kwargs):
366 #: Bypass the cache entirely.
367 if self._bypass_cache(unless, f, *args, **kwargs):
368 return self._call_fn(f, *args, **kwargs)
369
370 nonlocal source_check
371 if source_check is None:
372 source_check = self.source_check
373
374 try:
375 if make_cache_key is not None and callable(make_cache_key):
376 cache_key = make_cache_key(*args, **kwargs)
377 else:
378 cache_key = decorated_function.make_cache_key(
379 *args, use_request=True, **kwargs
380 )
381
382 if (
383 callable(forced_update)
384 and (
385 forced_update(*args, **kwargs)
386 if wants_args(forced_update)
387 else forced_update()
388 )
389 is True
390 ):
391 rv = None
392 found = False
393 else:
394 rv = self.cache.get(cache_key)
395 found = True
396
397 # If the value returned by cache.get() is None, it
398 # might be because the key is not found in the cache
399 # or because the cached value is actually None
400 if rv is None:
401 # If we're sure we don't need to cache None values
402 # (cache_none=False), don't bother checking for
403 # key existence, as it can lead to false positives
404 # if a concurrent call already cached the
405 # key between steps. This would cause us to
406 # return None when we shouldn't
407 if not cache_none:
408 found = False
409 else:
410 found = self.cache.has(cache_key)
411 except Exception:
412 if self.app.debug:
413 raise
414 logger.exception("Exception possibly due to cache backend.")
415 return self._call_fn(f, *args, **kwargs)
416 if found and self.app.debug:
417 logger.info(f"Cache used for key: {cache_key}")
418 if response_hit_indication:
419 g.flask_caching_hit_cache = found
420
421 def apply_caching(response):
422 if g.get("flask_caching_hit_cache"):
423 response.headers["hit_cache"] = g.flask_caching_hit_cache
424 return response
425
426 if "apply_caching" not in self.app.after_request_funcs[None]:
427 self.app.after_request_funcs[None].append(apply_caching)
428
429 if not found:
430 rv = self._call_fn(f, *args, **kwargs)
431 if inspect.isgenerator(rv):
432 rv = [val for val in rv]
433
434 if response_filter is None or response_filter(rv):
435 cache_timeout = decorated_function.cache_timeout
436 if isinstance(rv, CachedResponse):
437 cache_timeout = rv.timeout or cache_timeout
438 try:
439 self.cache.set(
440 cache_key,
441 rv,
442 timeout=cache_timeout,
443 )
444 except Exception:
445 if self.app.debug:
446 raise
447 logger.exception("Exception possibly due to cache backend.")
448 return rv
449
450 def default_make_cache_key(*args, **kwargs):
451 # Convert non-keyword arguments (which is the way
452 # `make_cache_key` expects them) to keyword arguments
453 # (the way `url_for` expects them)
454 argspec_args = get_arg_names(f)
455
456 for arg_name, arg in zip(argspec_args, args, strict=False):
457 kwargs[arg_name] = arg
458
459 use_request = kwargs.pop("use_request", False)
460 return _make_cache_key(args, kwargs, use_request=use_request)
461
462 def _make_cache_key_query_string():
463 """Create consistent keys for query string arguments.
464
465 Produces the same cache key regardless of argument order, e.g.,
466 both `?limit=10&offset=20` and `?offset=20&limit=10` will
467 always produce the same exact cache key.
468
469 If func is provided and is callable it will be used to hash
470 the function's source code and include it in the cache key.
471 This will only be done is source_check is True.
472 """
473
474 # Create a tuple of (key, value) pairs, where the key is the
475 # argument name and the value is its respective value. Order
476 # this tuple by key. Doing this ensures the cache key created
477 # is always the same for query string args whose keys/values
478 # are the same, regardless of the order in which they are
479 # provided.
480
481 args_as_sorted_tuple = tuple(
482 sorted(pair for pair in request.args.items(multi=True))
483 )
484 # ... now hash the sorted (key, value) tuple so it can be
485 # used as a key for cache. Turn them into bytes so that the
486 # hash function will accept them
487 args_as_bytes = str(args_as_sorted_tuple).encode()
488 cache_hash = hash_method(args_as_bytes)
489
490 # Use the source code if source_check is True and update the
491 # cache_hash before generating the hashing and using it in
492 # cache_key
493 if source_check and callable(f):
494 func_source_code = inspect.getsource(f)
495 cache_hash.update(func_source_code.encode("utf-8"))
496
497 cache_hash = str(cache_hash.hexdigest())
498
499 cache_key = request.path + cache_hash
500
501 return cache_key
502
503 def _make_cache_key(args, kwargs, use_request) -> str:
504 if query_string:
505 return _make_cache_key_query_string()
506 else:
507 if callable(key_prefix):
508 cache_key = key_prefix()
509 elif "%s" in key_prefix:
510 if use_request:
511 cache_key = key_prefix % request.path
512 else:
513 cache_key = key_prefix % url_for(f.__name__, **kwargs)
514 else:
515 cache_key = key_prefix
516
517 if source_check and callable(f):
518 func_source_code = inspect.getsource(f)
519 func_source_hash = hash_method(func_source_code.encode("utf-8"))
520 func_source_hash = str(func_source_hash.hexdigest())
521
522 cache_key += func_source_hash
523
524 return cache_key
525
526 decorated_function.uncached = f
527 decorated_function.cache_timeout = timeout
528 decorated_function.make_cache_key = default_make_cache_key
529
530 return decorated_function
531
532 return decorator
533
534 def _memvname(self, funcname: str) -> str:
535 return funcname + "_memver"
536
537 def _memoize_make_version_hash(self) -> str:
538 return base64.b64encode(uuid.uuid4().bytes)[:6].decode("utf-8")
539
540 def _memoize_version(
541 self,
542 f: Callable,
543 args: Any | None = None,
544 kwargs=None,
545 reset: bool = False,
546 delete: bool = False,
547 timeout: int | None = None,
548 forced_update: Union[bool, Callable] | None = False,
549 args_to_ignore: Any | None = None,
550 ) -> Union[tuple[str, str], tuple[str, None]]:
551 """Updates the hash version associated with a memoized function or
552 method.
553 """
554 fname, instance_fname = function_namespace(f, args=args)
555 version_key = self._memvname(fname)
556 fetch_keys = [version_key]
557
558 args_to_ignore = args_to_ignore or []
559 if "self" in args_to_ignore:
560 instance_fname = None
561
562 if instance_fname:
563 instance_version_key = self._memvname(instance_fname)
564 fetch_keys.append(instance_version_key)
565
566 # Only delete the per-instance version key or per-function version
567 # key but not both.
568 if delete:
569 self.cache.delete_many(fetch_keys[-1])
570 return fname, None
571
572 version_data_list = list(self.cache.get_many(*fetch_keys))
573 dirty = False
574
575 if (
576 callable(forced_update)
577 and (
578 forced_update(*(args or ()), **(kwargs or {}))
579 if wants_args(forced_update)
580 else forced_update()
581 )
582 is True
583 ):
584 # Mark key as dirty to update its TTL
585 dirty = True
586
587 if version_data_list[0] is None:
588 version_data_list[0] = self._memoize_make_version_hash()
589 dirty = True
590
591 if instance_fname and version_data_list[1] is None:
592 version_data_list[1] = self._memoize_make_version_hash()
593 dirty = True
594
595 # Only reset the per-instance version or the per-function version
596 # but not both.
597 if reset:
598 fetch_keys = fetch_keys[-1:]
599 version_data_list = [self._memoize_make_version_hash()]
600 dirty = True
601
602 if dirty:
603 self.cache.set_many(
604 dict(zip(fetch_keys, version_data_list, strict=False)), timeout=timeout
605 )
606
607 return fname, "".join(version_data_list)
608
609 def _memoize_make_cache_key(
610 self,
611 make_name: Callable | None = None,
612 timeout: Callable | None = None,
613 forced_update: bool = False,
614 hash_method: Callable = hashlib.md5,
615 source_check: bool | None = False,
616 args_to_ignore: Any | None = None,
617 ) -> Callable:
618 """Function used to create the cache_key for memoized functions."""
619
620 def make_cache_key(f, *args, **kwargs):
621 _timeout = getattr(timeout, "cache_timeout", timeout)
622 fname, version_data = self._memoize_version(
623 f,
624 args=args,
625 kwargs=kwargs,
626 timeout=_timeout,
627 forced_update=forced_update,
628 args_to_ignore=args_to_ignore,
629 )
630
631 #: this should have to be after version_data, so that it
632 #: does not break the delete_memoized functionality.
633 altfname = make_name(fname) if callable(make_name) else fname
634
635 if callable(f):
636 keyargs, keykwargs = self._memoize_kwargs_to_args(
637 f, *args, **kwargs, args_to_ignore=args_to_ignore
638 )
639 else:
640 keyargs, keykwargs = args, kwargs
641
642 updated = f"{altfname}{keyargs}{keykwargs}"
643
644 cache_key = hash_method()
645 cache_key.update(updated.encode("utf-8"))
646
647 # Use the source code if source_check is True and update the
648 # cache_key with the function's source.
649 if source_check and callable(f):
650 func_source_code = inspect.getsource(f)
651 cache_key.update(func_source_code.encode("utf-8"))
652
653 cache_key = base64.b64encode(cache_key.digest())[:16]
654 cache_key = cache_key.decode("utf-8")
655 cache_key += version_data
656
657 return cache_key
658
659 return make_cache_key
660
661 def _memoize_kwargs_to_args(self, f: Callable, *args, **kwargs) -> Any:
662 #: Inspect the arguments to the function
663 #: This allows the memoization to be the same
664 #: whether the function was called with
665 #: 1, b=2 is equivalent to a=1, b=2, etc.
666 new_args = []
667 arg_num = 0
668 args_to_ignore = kwargs.pop("args_to_ignore", None) or []
669
670 # If the function uses VAR_KEYWORD type of parameters,
671 # we need to pass these further
672 kw_keys_remaining = [key for key in kwargs.keys() if key not in args_to_ignore]
673 arg_names = get_arg_names(f)
674 args_len = len(arg_names)
675
676 for i in range(args_len):
677 arg_default = get_arg_default(f, i)
678 if arg_names[i] in args_to_ignore:
679 arg = None
680 arg_num += 1
681 elif i == 0 and arg_names[i] in ("self", "cls"):
682 #: use the id func of the class instance
683 #: this supports instance methods for
684 #: the memoized functions, giving more
685 #: flexibility to developers
686 arg = get_id(args[0])
687 arg_num += 1
688 elif arg_names[i] in kwargs:
689 arg = kwargs[arg_names[i]]
690 kw_keys_remaining.pop(kw_keys_remaining.index(arg_names[i]))
691 elif arg_num < len(args):
692 arg = args[arg_num]
693 arg_num += 1
694 elif arg_default:
695 arg = arg_default
696 arg_num += 1
697 else:
698 arg = None
699 arg_num += 1
700
701 #: Attempt to convert all arguments to a
702 #: hash/id or a representation?
703 #: Not sure if this is necessary, since
704 #: using objects as keys gets tricky quickly.
705 # if hasattr(arg, '__class__'):
706 # try:
707 # arg = hash(arg)
708 # except:
709 # arg = get_id(arg)
710
711 #: Or what about a special __cacherepr__ function
712 #: on an object, this allows objects to act normal
713 #: upon inspection, yet they can define a representation
714 #: that can be used to make the object unique in the
715 #: cache key. Given that a case comes across that
716 #: an object "must" be used as a cache key
717 # if hasattr(arg, '__cacherepr__'):
718 # arg = arg.__cacherepr__
719
720 new_args.append(arg)
721
722 new_args.extend(args[len(arg_names) :])
723 return (
724 tuple(new_args),
725 OrderedDict(
726 sorted((k, v) for k, v in kwargs.items() if k in kw_keys_remaining)
727 ),
728 )
729
730 def _bypass_cache(
731 self, unless: Callable | None, f: Callable, *args, **kwargs
732 ) -> bool:
733 """Determines whether or not to bypass the cache by calling unless().
734 Supports both unless() that takes in arguments and unless()
735 that doesn't.
736 """
737 bypass_cache = False
738
739 if callable(unless):
740 # If unless() takes args, pass them in.
741 if wants_args(unless):
742 if unless(f, *args, **kwargs) is True:
743 bypass_cache = True
744 elif unless() is True:
745 bypass_cache = True
746
747 return bypass_cache
748
749 def memoize(
750 self,
751 timeout: int | None = None,
752 make_name: Callable | None = None,
753 unless: Callable | None = None,
754 forced_update: Callable | None = None,
755 response_filter: Callable | None = None,
756 hash_method: Callable = hashlib.md5,
757 cache_none: bool = False,
758 source_check: bool | None = None,
759 args_to_ignore: Any | None = None,
760 ) -> Callable:
761 """Use this to cache the result of a function, taking its arguments
762 into account in the cache key.
763
764 Information on
765 `Memoization <http://en.wikipedia.org/wiki/Memoization>`_.
766
767 Example::
768
769 @cache.memoize(timeout=50)
770 def big_foo(a, b):
771 return a + b + random.randrange(0, 1000)
772
773 .. code-block:: pycon
774
775 >>> big_foo(5, 2)
776 753
777 >>> big_foo(5, 3)
778 234
779 >>> big_foo(5, 2)
780 753
781
782 .. versionadded:: 0.4
783 The returned decorated function now has three function attributes
784 assigned to it.
785
786 **uncached**
787 The original undecorated function. readable only
788
789 **cache_timeout**
790 The cache timeout value for this function.
791 For a custom value to take affect, this must be
792 set before the function is called.
793
794 readable and writable
795
796 **make_cache_key**
797 A function used in generating the cache_key used.
798
799 readable and writable
800
801
802 :param timeout: Default None. If set to an integer, will cache for that
803 amount of time. Unit of time is in seconds.
804 :param make_name: Default None. If set this is a function that accepts
805 a single argument, the function name, and returns a
806 new string to be used as the function name.
807 If not set then the function name is used.
808 :param unless: Default None. Cache will *always* execute the caching
809 facilities unless this callable is true.
810 This will bypass the caching entirely.
811 :param forced_update: Default None. If this callable is true,
812 cache value will be updated regardless cache
813 is expired or not. Useful for background
814 renewal of cached functions.
815 :param response_filter: Default None. If not None, the callable is
816 invoked after the cached funtion evaluation,
817 and is given one arguement, the response
818 content. If the callable returns False, the
819 content will not be cached. Useful to prevent
820 caching of code 500 responses.
821 :param hash_method: Default hashlib.md5. The hash method used to
822 generate the keys for cached results.
823 :param cache_none: Default False. If set to True, add a key exists
824 check when cache.get returns None. This will likely
825 lead to wrongly returned None values in concurrent
826 situations and is not recommended to use.
827
828 :param source_check: Default None. If None will use the value set by
829 CACHE_SOURCE_CHECK.
830 If True, include the function's source code in the
831 hash to avoid using cached values when the source
832 code has changed and the input values remain the
833 same. This ensures that the cache_key will be
834 formed with the function's source code hash in
835 addition to other parameters that may be included
836 in the formation of the key.
837 :param args_to_ignore: List of arguments that will be ignored while
838 generating the cache key. Default to None.
839 This means that those arguments may change
840 without affecting the cache value that will be
841 returned.
842
843 .. versionadded:: 0.5
844 params ``make_name``, ``unless``
845
846 .. versionadded:: 1.10
847 params ``args_to_ignore``
848 """
849
850 def memoize(f):
851 @functools.wraps(f)
852 def decorated_function(*args, **kwargs):
853 #: bypass cache
854 if self._bypass_cache(unless, f, *args, **kwargs):
855 return self._call_fn(f, *args, **kwargs)
856
857 nonlocal source_check
858 if source_check is None:
859 source_check = self.source_check
860
861 try:
862 cache_key = decorated_function.make_cache_key(f, *args, **kwargs)
863
864 if (
865 callable(forced_update)
866 and (
867 forced_update(*args, **kwargs)
868 if wants_args(forced_update)
869 else forced_update()
870 )
871 is True
872 ):
873 rv = None
874 found = False
875 else:
876 rv = self.cache.get(cache_key)
877 found = True
878
879 # If the value returned by cache.get() is None, it
880 # might be because the key is not found in the cache
881 # or because the cached value is actually None
882 if rv is None:
883 # If we're sure we don't need to cache None values
884 # (cache_none=False), don't bother checking for
885 # key existence, as it can lead to false positives
886 # if a concurrent call already cached the
887 # key between steps. This would cause us to
888 # return None when we shouldn't
889 if not cache_none:
890 found = False
891 else:
892 found = self.cache.has(cache_key)
893 except Exception:
894 if self.app.debug:
895 raise
896 logger.exception("Exception possibly due to cache backend.")
897 return self._call_fn(f, *args, **kwargs)
898
899 if not found:
900 rv = self._call_fn(f, *args, **kwargs)
901 if inspect.isgenerator(rv):
902 rv = [val for val in rv]
903
904 if response_filter is None or response_filter(rv):
905 try:
906 self.cache.set(
907 cache_key,
908 rv,
909 timeout=decorated_function.cache_timeout,
910 )
911 except Exception:
912 if self.app.debug:
913 raise
914 logger.exception("Exception possibly due to cache backend.")
915 return rv
916
917 decorated_function.uncached = f
918 decorated_function.cache_timeout = timeout
919 decorated_function.make_cache_key = self._memoize_make_cache_key(
920 make_name=make_name,
921 timeout=decorated_function,
922 forced_update=forced_update,
923 hash_method=hash_method,
924 source_check=source_check,
925 args_to_ignore=args_to_ignore,
926 )
927 decorated_function.delete_memoized = lambda: self.delete_memoized(f)
928
929 return decorated_function
930
931 return memoize
932
933 def delete_memoized(self, f, *args, **kwargs) -> None:
934 """Deletes the specified functions caches, based by given parameters.
935 If parameters are given, only the functions that were memoized
936 with them will be erased. Otherwise all versions of the caches
937 will be forgotten.
938
939 Example::
940
941 @cache.memoize(50)
942 def random_func():
943 return random.randrange(1, 50)
944
945 @cache.memoize()
946 def param_func(a, b):
947 return a+b+random.randrange(1, 50)
948
949 .. code-block:: pycon
950
951 >>> random_func()
952 43
953 >>> random_func()
954 43
955 >>> cache.delete_memoized(random_func)
956 >>> random_func()
957 16
958 >>> param_func(1, 2)
959 32
960 >>> param_func(1, 2)
961 32
962 >>> param_func(2, 2)
963 47
964 >>> cache.delete_memoized(param_func, 1, 2)
965 >>> param_func(1, 2)
966 13
967 >>> param_func(2, 2)
968 47
969
970 Delete memoized is also smart about instance methods vs class methods.
971
972 When passing a instancemethod, it will only clear the cache related
973 to that instance of that object. (object uniqueness can be overridden
974 by defining the __repr__ method, such as user id).
975
976 When passing a classmethod, it will clear all caches related across
977 all instances of that class.
978
979 Example::
980
981 class Adder(object):
982 @cache.memoize()
983 def add(self, b):
984 return b + random.random()
985
986 .. code-block:: pycon
987
988 >>> adder1 = Adder()
989 >>> adder2 = Adder()
990 >>> adder1.add(3)
991 3.23214234
992 >>> adder2.add(3)
993 3.60898509
994 >>> cache.delete_memoized(adder1.add)
995 >>> adder1.add(3)
996 3.01348673
997 >>> adder2.add(3)
998 3.60898509
999 >>> cache.delete_memoized(Adder.add)
1000 >>> adder1.add(3)
1001 3.53235667
1002 >>> adder2.add(3)
1003 3.72341788
1004
1005 :param fname: The memoized function.
1006 :param \\*args: A list of positional parameters used with
1007 memoized function.
1008 :param \\**kwargs: A dict of named parameters used with
1009 memoized function.
1010
1011 .. note::
1012
1013 Flask-Caching uses inspect to order kwargs into positional args when
1014 the function is memoized. If you pass a function reference into
1015 ``fname``, Flask-Caching will be able to place the args/kwargs in
1016 the proper order, and delete the positional cache.
1017
1018 However, if ``delete_memoized`` is just called with the name of the
1019 function, be sure to pass in potential arguments in the same order
1020 as defined in your function as args only, otherwise Flask-Caching
1021 will not be able to compute the same cache key and delete all
1022 memoized versions of it.
1023
1024 .. note::
1025
1026 Flask-Caching maintains an internal random version hash for
1027 the function. Using delete_memoized will only swap out
1028 the version hash, causing the memoize function to recompute
1029 results and put them into another key.
1030
1031 This leaves any computed caches for this memoized function within
1032 the caching backend.
1033
1034 It is recommended to use a very high timeout with memoize if using
1035 this function, so that when the version hash is swapped, the old
1036 cached results would eventually be reclaimed by the caching
1037 backend.
1038 """
1039 if not callable(f):
1040 raise TypeError(
1041 "Deleting messages by relative name is not supported, please "
1042 "use a function reference."
1043 )
1044
1045 if not (args or kwargs):
1046 self._memoize_version(f, reset=True)
1047 else:
1048 cache_key = f.make_cache_key(f.uncached, *args, **kwargs)
1049 self.cache.delete(cache_key)
1050
1051 def delete_memoized_verhash(self, f: Callable, *args) -> None:
1052 """Delete the version hash associated with the function.
1053
1054 .. warning::
1055
1056 Performing this operation could leave keys behind that have
1057 been created with this version hash. It is up to the application
1058 to make sure that all keys that may have been created with this
1059 version hash at least have timeouts so they will not sit orphaned
1060 in the cache backend.
1061 """
1062 if not callable(f):
1063 raise TypeError(
1064 "Deleting messages by relative name is not supported, please"
1065 "use a function reference."
1066 )
1067
1068 self._memoize_version(f, delete=True)