Make decorator responsibe for applying the prefix

The key builder should not have to fetch the prefix separately, as this
makes creating custom key builders that much harder.
This commit is contained in:
Martijn Pieters
2023-05-10 17:46:48 +01:00
parent 5f2fcf3581
commit d9965a45e5
2 changed files with 6 additions and 11 deletions

View File

@@ -121,6 +121,7 @@ def cache(
) or not FastAPICache.get_enable(): ) or not FastAPICache.get_enable():
return await ensure_async_func(*args, **kwargs) return await ensure_async_func(*args, **kwargs)
prefix = FastAPICache.get_prefix()
coder = coder or FastAPICache.get_coder() coder = coder or FastAPICache.get_coder()
expire = expire or FastAPICache.get_expire() expire = expire or FastAPICache.get_expire()
key_builder = key_builder or FastAPICache.get_key_builder() key_builder = key_builder or FastAPICache.get_key_builder()
@@ -128,7 +129,7 @@ def cache(
cache_key = key_builder( cache_key = key_builder(
func, func,
namespace, f"{prefix}:{namespace}",
request=request, request=request,
response=response, response=response,
args=args, args=args,

View File

@@ -13,13 +13,7 @@ def default_key_builder(
args: Optional[tuple[Any, ...]] = None, args: Optional[tuple[Any, ...]] = None,
kwargs: Optional[dict[str, Any]] = None, kwargs: Optional[dict[str, Any]] = None,
) -> str: ) -> str:
from fastapi_cache import FastAPICache cache_key = hashlib.md5( # nosec:B303
f"{func.__module__}:{func.__name__}:{args}:{kwargs}".encode()
prefix = f"{FastAPICache.get_prefix()}:{namespace}:" ).hexdigest()
cache_key = ( return f"{namespace}:{cache_key}"
prefix
+ hashlib.md5( # nosec:B303
f"{func.__module__}:{func.__name__}:{args}:{kwargs}".encode()
).hexdigest()
)
return cache_key