From 1795c048d173a3986ec9274a1002ee9ebb02509d Mon Sep 17 00:00:00 2001 From: Tobias Schmocker Date: Fri, 4 Feb 2022 16:37:18 +0100 Subject: [PATCH 1/2] add cache-control to response after setting the cache --- fastapi_cache/decorator.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/fastapi_cache/decorator.py b/fastapi_cache/decorator.py index 7b60408..10c53ca 100644 --- a/fastapi_cache/decorator.py +++ b/fastapi_cache/decorator.py @@ -47,7 +47,7 @@ def cache( if ret is not None: return coder.decode(ret) ret = await func(*args, **kwargs) - await backend.set(cache_key, coder.encode(ret), expire or FastAPICache.get_expire()) + await backend.set(cache_key, coder.encode(ret), expire) return ret if request.method != "GET": @@ -64,7 +64,11 @@ def cache( return coder.decode(ret) ret = await func(*args, **kwargs) - await backend.set(cache_key, coder.encode(ret), expire or FastAPICache.get_expire()) + encoded_ret = coder.encode(ret) + await backend.set(cache_key, encoded_ret, expire) + response.headers["Cache-Control"] = f"private, max-age={expire}" + etag = f"W/{hash(encoded_ret)}" + response.headers["ETag"] = etag return ret return inner From e5250c7f582c3e92b95a566f7fb999e5170f6f47 Mon Sep 17 00:00:00 2001 From: Tobias Schmocker Date: Fri, 4 Feb 2022 16:41:42 +0100 Subject: [PATCH 2/2] remove private from cache-control --- fastapi_cache/decorator.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fastapi_cache/decorator.py b/fastapi_cache/decorator.py index 10c53ca..82be02c 100644 --- a/fastapi_cache/decorator.py +++ b/fastapi_cache/decorator.py @@ -66,7 +66,7 @@ def cache( ret = await func(*args, **kwargs) encoded_ret = coder.encode(ret) await backend.set(cache_key, encoded_ret, expire) - response.headers["Cache-Control"] = f"private, max-age={expire}" + response.headers["Cache-Control"] = f"max-age={expire}" etag = f"W/{hash(encoded_ret)}" response.headers["ETag"] = etag return ret