long2ice / fastapi-cache

fastapi-cache is a tool to cache fastapi response and function result, with backends support redis and memcached.
https://github.com/long2ice/fastapi-cache
Apache License 2.0
1.36k stars 165 forks source link

Overriding `Cache-Control` header #256

Open joshfermin opened 1 year ago

joshfermin commented 1 year ago

Hello, is there any way to override the cache-control header?

I am running into an issue where I need to clear the cache key on update, but since fastapi-cache is setting the cache-control header I am getting a 200 OK (from disk cache) response. I need to be able to override the cache-control header so that we don't keep stale data

arkhodakov commented 1 year ago

I encountered the same problem. I had to create a simple middleware to override the header without changing the library code.

class RouterCacheControlResetMiddleware(BaseHTTPMiddleware):
    """Disable Response headers Cache-Control (set to 'no-cache').

    The initial reason for this is that the fastapi-cache library sets the max-age param of the header
    equal to the expire parameter that is provided to the caching layer (Redis),
    so the response is also cached on the browser side, which in most cases is unnecessary."""
    async def dispatch(self, request: Request, call_next: Callable) -> Response:
        response: Response = await call_next(request)
        response.headers.update({
            "Cache-Control": "no-cache"
        })
        return response