fastapi-cache
fastapi-cache copied to clipboard
[question] Cache results respecting raw request path?
I have a function that utilizes the raw starlette request to parse the path_parameters in order to provide dynamic content. Right now, the cache implementation returns the same cached result regardless of the path. Would there be any way to intercept the args/kwargs in the decorator to provide a more in-depth cache system?
My code looks something like:
@cache()
async def get(request: Request):
# return content based on request[some_key]
Hello @V3ntus, Maybe using the key_builder like so would help?
def key_builder(
func,
namespace: Optional[str] = "",
request: Optional[Request] = None,
response: Optional[Response] = None,
args: Optional[tuple] = None,
kwargs: Optional[dict] = None,
):
key = f"{request.method}:{request.url}:{request.body()}"
cache_key = (
prefix
+ hashlib.md5( # nosec:B303
key.encode()
).hexdigest()
)
and then provide it like so: @cache(key_builder=key_builder)
This is another potential 'advanced use' documentation example.