fastapi-cache icon indicating copy to clipboard operation
fastapi-cache copied to clipboard

[question] Cache results respecting raw request path?

Open V3ntus opened this issue 2 years ago • 2 comments

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]

V3ntus avatar Jun 13 '22 03:06 V3ntus

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)

jegork avatar Aug 19 '22 20:08 jegork

This is another potential 'advanced use' documentation example.

mjpieters avatar May 15 '23 11:05 mjpieters