Debian Codegraph @

src/flask_caching/utils.py

raw
1 import inspect
2 import math
3 import string
4 import sys
5 from collections.abc import Callable
6 from collections.abc import Iterable
7 from collections.abc import Mapping
8 from datetime import timedelta
9 from typing import Any
10 from typing import cast
11 from typing import TypeAlias
12 from urllib.parse import parse_qsl
13
14 from werkzeug.datastructures import MultiDict
15
16 if sys.version_info >= (3, 14):
17 import annotationlib
18
19 def _signature(f: Callable) -> inspect.Signature:
20 return inspect.signature(f, annotation_format=annotationlib.Format.FORWARDREF)
21 else:
22 _signature = inspect.signature
23
24 TEMPLATE_FRAGMENT_KEY_TEMPLATE = "_template_fragment_cache_%s%s"
25 # Used to remove control characters and whitespace from cache keys.
26 valid_chars = set(string.ascii_letters + string.digits + "_.")
27 del_chars = "".join(c for c in map(chr, range(256)) if c not in valid_chars)
28 null_control = str.maketrans({k: None for k in del_chars})
29
30 _QueryArgs: TypeAlias = str | Mapping[str, Any] | Iterable[tuple[str, Any]]
31 _Timeout: TypeAlias = int | timedelta
32
33
34 def normalize_timeout(timeout: _Timeout | str | None) -> int | None:
35 """Convert a ``timedelta`` timeout to whole seconds. A subsecond timeout
36 (i.e. miliseconds) is rounded up to a whole second.
37 A subsecond timeout does not turn into ``0``!
38 """
39 if isinstance(timeout, str):
40 timeout = int(timeout)
41
42 if isinstance(timeout, timedelta):
43 return math.ceil(timeout.total_seconds())
44 return timeout
45
46
47 def wants_args(f: Callable[..., Any]) -> bool:
48 """Check if the function wants any positional, *args, or **kwargs arguments."""
49 return any(
50 p.kind != inspect.Parameter.KEYWORD_ONLY for p in get_function_parameters(f)
51 )
52
53
54 def wants_extra_args(f: Callable[..., Any]) -> bool:
55 """Check if the function wants an additional argument beside
56 its first positional one.
57 """
58 return (
59 sum(
60 p.kind != inspect.Parameter.KEYWORD_ONLY for p in get_function_parameters(f)
61 )
62 > 1
63 )
64
65
66 def get_function_parameters(f: Callable[..., Any]) -> list[inspect.Parameter]:
67 """Get function parameters
68 :param f
69 :return: Parameter list of function
70 """
71 return list(_signature(f).parameters.values())
72
73
74 def get_arg_names(f: Callable[..., Any]) -> list[str]:
75 """Return arguments of function
76 :param f:
77 :return: String list of arguments
78 """
79 return [
80 parameter.name
81 for parameter in get_function_parameters(f)
82 if parameter.kind == parameter.POSITIONAL_OR_KEYWORD
83 ]
84
85
86 def get_arg_default(f: Callable[..., Any], position: int) -> Any:
87 arg = get_function_parameters(f)[position]
88 arg_def = arg.default
89 return arg_def if arg_def != inspect.Parameter.empty else None
90
91
92 def query_args_as_pairs(query_args: _QueryArgs) -> list[tuple[str, str]]:
93 """Convert the accepted query args to (key, value) pairs."""
94 if isinstance(query_args, str):
95 return parse_qsl(query_args.lstrip("?"), keep_blank_values=True)
96 if isinstance(query_args, MultiDict):
97 items: Iterable[tuple[str, Any]] = cast(
98 "MultiDict[str, Any]", query_args
99 ).items(multi=True)
100 elif isinstance(query_args, Mapping):
101 items = cast("Mapping[str, Any]", query_args).items()
102 else:
103 items = query_args
104
105 return [(key, str(value)) for key, value in items]
106
107
108 def get_id(obj: Any) -> str:
109 caching_id = getattr(obj, "__caching_id__", None)
110 if caching_id is None:
111 return repr(obj)
112 return str(caching_id())
113
114
115 def function_namespace(
116 f: Callable[..., Any], args: Any = None
117 ) -> tuple[str, str | None]:
118 """Attempts to return a unique namespace for the function."""
119 m_args = get_arg_names(f)
120
121 instance_token = None
122
123 instance_self = getattr(f, "__self__", None)
124
125 if instance_self and not inspect.isclass(instance_self):
126 instance_token = get_id(instance_self)
127 elif m_args and m_args[0] == "self" and args:
128 instance_token = get_id(args[0])
129
130 module = f.__module__
131
132 if m_args and m_args[0] == "cls" and not (args and inspect.isclass(args[0])):
133 raise ValueError(
134 "When using `delete_memoized` on a "
135 "`@classmethod` you must provide the "
136 "class as the first argument"
137 )
138
139 if hasattr(f, "__qualname__"):
140 name = f.__qualname__
141 else:
142 klass = getattr(f, "__self__", None)
143
144 if klass and not inspect.isclass(klass):
145 klass = klass.__class__
146
147 if not klass:
148 klass = getattr(f, "im_class", None)
149
150 if not klass:
151 if m_args and args:
152 if m_args[0] == "self":
153 klass = args[0].__class__
154 elif m_args[0] == "cls":
155 klass = args[0]
156
157 if klass:
158 name = klass.__name__ + "." + f.__name__
159 else:
160 name = f.__name__
161
162 ns = ".".join((module, name)).translate(null_control)
163
164 ins = (
165 ".".join((module, name, instance_token)).translate(null_control)
166 if instance_token
167 else None
168 )
169
170 return ns, ins
171
172
173 def make_template_fragment_key(
174 fragment_name: str, vary_on: list[str] | None = None
175 ) -> str:
176 """Make a cache key for a specific fragment name."""
177 if vary_on:
178 fragment_name = f"{fragment_name}_"
179 else:
180 vary_on = []
181 return TEMPLATE_FRAGMENT_KEY_TEMPLATE % (fragment_name, "_".join(vary_on))
182
183
184 def join_generator(rv: Any) -> Any:
185 """Used to join strings and bytes together when inspect.isgenerator(rv) = True"""
186 chunks = list(rv)
187
188 if all(isinstance(chunk, str) for chunk in chunks):
189 return "".join(chunks)
190 if all(isinstance(chunk, bytes) for chunk in chunks):
191 return b"".join(chunks)
192 return chunks