Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions fastapi_cache/decorator.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import hashlib
import logging
import sys
from functools import wraps
Expand Down Expand Up @@ -66,6 +67,16 @@ def _locate_param(
return param


def _compute_etag(data: bytes) -> str:
"""Compute a deterministic ETag hash from cache data.

Uses MD5 for speed since this is for caching, not security.
Unlike Python's built-in hash(), this produces consistent values
across different processes and service restarts.
"""
return hashlib.md5(data).hexdigest()


def _uncacheable(request: Optional[Request]) -> bool:
"""Determine if this request should not be cached

Expand Down Expand Up @@ -199,14 +210,14 @@ async def ensure_async_func(*args: P.args, **kwargs: P.kwargs) -> R:
response.headers.update(
{
"Cache-Control": f"max-age={expire}",
"ETag": f"W/{hash(to_cache)}",
"ETag": f"W/{_compute_etag(to_cache)}",
cache_status_header: "MISS",
}
)

else: # cache hit
if response:
etag = f"W/{hash(cached)}"
etag = f"W/{_compute_etag(cached)}"
response.headers.update(
{
"Cache-Control": f"max-age={ttl}",
Expand Down