long2ice/fastapi-cache

Empty response in key builder

ksh-b opened this issue · 2 comments

I have a custom key builder like this:

def key_builder(
    func: Callable[..., Any],
    namespace: str = "",
    *,
    request: Optional[Request] = None,
    response: Optional[Response] = None,
    args: Tuple[Any, ...],
    kwargs: Dict[str, Any],
) -> str:
    cache_key = hashlib.md5(  # noqa: S324
        f"{kwargs.get('xyz')}".encode()
    ).hexdigest()
    print(response.body)
    return f"{namespace}:{cache_key}"
    

and using it on a get method abc using @cache(key_builder=key_builder)

@router.get("/abc")
@cache(key_builder=key_builder)
async def abc(
        *, session: Session = Depends(get_session), xyz: str
):
    return {"hello":"world"}

but the response.body prints nothing, even though the method abc returns a dict.

Am I missing something here. Thanks.

I have browsed some of the relevant code of fastapi-cache and fastapi, and the following is my analysis:

The response parameter in key_builder is just an empty response object, which is generated by this line of code in fastapi.

https://github.com/tiangolo/fastapi/blob/6f6e786979eb3156b85e7c2f44d0b8af5cf0af17/fastapi/dependencies/utils.py#L522-L544

Actually, the response is created here.

https://github.com/tiangolo/fastapi/blob/6f6e786979eb3156b85e7c2f44d0b8af5cf0af17/fastapi/routing.py#L315-L326

Simply put, the response in key_builder is not the actual response; it can only be used to set the response headers, as it appears to be the case at the moment.

I hope this helps you

Thanks for looking.
I dont know if its possible, but having response body in key_builder might be useful for some cases.