Debian Codegraph @

src/flask_caching/backends/filesystemcache.py

raw
1 """
2 flask_caching.backends.filesystem
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 The filesystem caching backend.
6
7 :copyright: (c) 2018 by Peter Justin.
8 :copyright: (c) 2010 by Thadeus Burgess.
9 :license: BSD, see LICENSE for more details.
10 """
11
12 import hashlib
13 import logging
14 import warnings
15 from typing import Any
16
17 from cachelib import FileSystemCache as CachelibFileSystemCache
18 from flask import Flask
19
20 from flask_caching.backends.base import BaseCache
21
22 logger = logging.getLogger(__name__)
23
24
25 class FileSystemCache(BaseCache, CachelibFileSystemCache):
26 """A cache that stores the items on the file system. This cache depends
27 on being the only user of the ``cache_dir``. Make absolutely sure that
28 nobody but this cache stores files there or otherwise the cache will
29 randomly delete files therein.
30
31 :param cache_dir: the directory where cache files are stored.
32 :param threshold: the maximum number of items the cache stores before
33 it starts deleting some. A threshold value of 0
34 indicates no threshold.
35 :param default_timeout: the default timeout that is used if no timeout is
36 specified on :meth:`~BaseCache.set`. A timeout of
37 0 indicates that the cache never expires.
38 :param mode: the file mode wanted for the cache files, default 0600
39 :param hash_method: Default :func:`~hashlib.sha256`. The hash method used to
40 generate the filename for cached results.
41 :param ignore_delete_many_errors: If set to ``False`` the ``delete_many``
42 method raises a ``RuntimeError`` in case
43 a key couldn't be deleted.
44 Defaults to ``False``.
45 :param ignore_errors: Deprecated alias for ``ignore_delete_many_errors``.
46
47 .. deprecated:: 2.5.0
48 Will be removed in the next version.
49 """
50
51 def __init__(
52 self,
53 cache_dir: str,
54 threshold: int = 500,
55 default_timeout: int = 300,
56 mode: int = 0o600,
57 hash_method: Any = hashlib.sha256,
58 ignore_delete_many_errors: bool = False,
59 ignore_errors: bool | None = None,
60 ) -> None:
61 if ignore_errors is not None:
62 warnings.warn(
63 "'ignore_errors' is deprecated and will be removed in the next "
64 "version. Use 'ignore_delete_many_errors' instead.",
65 DeprecationWarning,
66 stacklevel=2,
67 )
68 ignore_delete_many_errors = ignore_errors
69
70 CachelibFileSystemCache.__init__(
71 self,
72 cache_dir=cache_dir,
73 threshold=threshold,
74 default_timeout=default_timeout,
75 mode=mode,
76 hash_method=hash_method,
77 ignore_delete_many_errors=ignore_delete_many_errors,
78 )
79
80 @classmethod
81 def factory(
82 cls,
83 app: Flask,
84 config: dict[str, Any],
85 args: list[Any],
86 kwargs: dict[str, Any],
87 ) -> "FileSystemCache":
88 args.insert(0, config["CACHE_DIR"])
89 kwargs.update(
90 dict(
91 threshold=config["CACHE_THRESHOLD"],
92 hash_method=config["CACHE_FILE_HASH_METHOD"],
93 )
94 )
95 return cls(*args, **kwargs)