From d9965a45e5509f9035b6c7d41aef94f3b3a107ef Mon Sep 17 00:00:00 2001 From: Martijn Pieters Date: Wed, 10 May 2023 17:46:48 +0100 Subject: [PATCH] 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. --- fastapi_cache/decorator.py | 3 ++- fastapi_cache/key_builder.py | 14 ++++---------- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/fastapi_cache/decorator.py b/fastapi_cache/decorator.py index 534a11c..679e221 100644 --- a/fastapi_cache/decorator.py +++ b/fastapi_cache/decorator.py @@ -121,6 +121,7 @@ def cache( ) or not FastAPICache.get_enable(): return await ensure_async_func(*args, **kwargs) + prefix = FastAPICache.get_prefix() coder = coder or FastAPICache.get_coder() expire = expire or FastAPICache.get_expire() key_builder = key_builder or FastAPICache.get_key_builder() @@ -128,7 +129,7 @@ def cache( cache_key = key_builder( func, - namespace, + f"{prefix}:{namespace}", request=request, response=response, args=args, diff --git a/fastapi_cache/key_builder.py b/fastapi_cache/key_builder.py index c588889..c680619 100644 --- a/fastapi_cache/key_builder.py +++ b/fastapi_cache/key_builder.py @@ -13,13 +13,7 @@ def default_key_builder( args: Optional[tuple[Any, ...]] = None, kwargs: Optional[dict[str, Any]] = None, ) -> str: - from fastapi_cache import FastAPICache - - prefix = f"{FastAPICache.get_prefix()}:{namespace}:" - cache_key = ( - prefix - + hashlib.md5( # nosec:B303 - f"{func.__module__}:{func.__name__}:{args}:{kwargs}".encode() - ).hexdigest() - ) - return cache_key + cache_key = hashlib.md5( # nosec:B303 + f"{func.__module__}:{func.__name__}:{args}:{kwargs}".encode() + ).hexdigest() + return f"{namespace}:{cache_key}"