Skip to content

FastAPICache.Clear(namespace...) does not work with custom key_builder #571

Description

@Nickopusan13

Hello,
I'm having an issue with FastAPICache.clear() when using a custom key_builder.

The caching itself works perfectly:

@cache(expire=300, key_builder=create_client_key_builder("clients:single"))
async def get_single_client(...):
    ...

The key appears correctly in Redis like this:

clients:single:user:3:client_id:3:no-params

But when I try to clear it, nothing happens:

await FastAPICache.clear(
    namespace=f"clients:single:user:{current_user.id}:client_id:{client_id}:no-params"
)

Even though the string I'm passing is exactly the same as the key in Redis.

Right now I'm doing this and it works:

await redis_client.delete(
    f"clients:single:user:{current_user.id}:client_id:{client_id}:no-params"
)

Key Builder

def create_client_key_builder(namespace: str):
    def builder(func, *args, **kwargs):
        request = kwargs.get("request")
        current_user = getattr(request.state, "user", None)
        user_id = getattr(current_user, "id", "anonymous")
        client_id = kwargs.get("client_id") or request.path_params.get("client_id")
        query_params = request.url.query or "no-params"
        return f"{namespace}:user:{user_id}:client_id:{client_id}:{query_params}"
    return builder

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions