11"""Helper functions for generating cache keys."""
22
3+ from __future__ import annotations
4+
35from inspect import Signature , signature
46from typing import TYPE_CHECKING , Any , Callable
57
68from fastapi import Request , Response
79
8- from fastapi_redis_cache .types import ArgType , SigParameters
9-
1010if TYPE_CHECKING : # pragma: no cover
1111 from collections import OrderedDict
1212
13+ from fastapi_redis_cache .types import ArgType , SigParameters
14+
1315ALWAYS_IGNORE_ARG_TYPES = [Response , Request ]
1416
1517
1618def get_cache_key ( # noqa: D417
1719 prefix : str ,
20+ tag : str | None ,
1821 ignore_arg_types : list [ArgType ],
1922 func : Callable [..., Any ],
2023 * args : list [Any ],
@@ -25,6 +28,9 @@ def get_cache_key( # noqa: D417
2528 Args:
2629 prefix (`str`): Customizable namespace value that will prefix all cache
2730 keys.
31+ tag (`str`): Customizable tag value that will be inserted into the
32+ cache key. This can be used to group related keys together or to
33+ help expire a key in other routes.
2834 ignore_arg_types (`list[ArgType]`): Each argument to the API endpoint
2935 function is used to compose the cache key by calling `str(arg)`. If
3036 there are any keys that should not be used in this way (i.e.,
@@ -42,17 +48,18 @@ def get_cache_key( # noqa: D417
4248 ignore_arg_types .extend (ALWAYS_IGNORE_ARG_TYPES )
4349 ignore_arg_types = list (set (ignore_arg_types ))
4450 prefix = f"{ prefix } :" if prefix else ""
51+ tag_string = f"::{ tag } " if tag else ""
4552
4653 sig = signature (func )
4754 sig_params = sig .parameters
4855 func_args = get_func_args (sig , * args , ** kwargs )
4956 args_str = get_args_str (sig_params , func_args , ignore_arg_types )
50- return f"{ prefix } { func .__module__ } .{ func .__name__ } ({ args_str } )"
57+ return f"{ prefix } { func .__module__ } .{ func .__name__ } ({ args_str } ){ tag_string } "
5158
5259
5360def get_func_args (
5461 sig : Signature , * args : list [Any ], ** kwargs : dict [Any , Any ]
55- ) -> " OrderedDict[str, Any]" :
62+ ) -> OrderedDict [str , Any ]:
5663 """Return a dict object containing name and value of function arguments."""
5764 func_args = sig .bind (* args , ** kwargs )
5865 func_args .apply_defaults ()
@@ -61,7 +68,7 @@ def get_func_args(
6168
6269def get_args_str (
6370 sig_params : SigParameters ,
64- func_args : " OrderedDict[str, Any]" ,
71+ func_args : OrderedDict [str , Any ],
6572 ignore_arg_types : list [ArgType ],
6673) -> str :
6774 """Return a string with name and value of all args.
0 commit comments