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

Overriding `Cache-Control` header

Open joshfermin opened this issue 2 years ago • 1 comments

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

joshfermin avatar Aug 07 '23 17:08 joshfermin

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

arkhodakov avatar Sep 26 '23 12:09 arkhodakov