Skip to content
Merged
Show file tree
Hide file tree
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
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@ jobs:
pip install -e . mypy pytest httpx
- name: Mypy changed Python files
run: |
files=$(git diff --name-only origin/stable...HEAD -- '*.py')
files=$(git diff --name-only origin/stable...HEAD -- '*.py' ':!examples/*')
if [ -n "$files" ]; then
mypy --python-version 3.12 --ignore-missing-imports $files
mypy --config-file=/dev/null --python-version 3.12 --ignore-missing-imports --follow-imports=skip $files
else
echo "No Python files changed"
fi
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/towncrier.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ jobs:
- name: Install towncrier
run: |
python -m pip install --upgrade pip
pip install "towncrier>=22.12,<23"
pip install "towncrier>=26,<27"
- name: Check changelog fragment
run: |
if [[ "${{ contains(github.event.pull_request.labels.*.name, 'skip-changelog') }}" == "true" ]]; then
Expand Down
32 changes: 16 additions & 16 deletions COMPATIBILITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,22 +121,22 @@ Status definitions:

## Intentional behavior changes

These are bug fixes targeted for `0.3.0`. The current alpha does not include all of them.
Each one will be documented in [`MIGRATION.md`](MIGRATION.md) and covered by a regression
test when implemented.

| Version | Change | Why |
|---|---|---|
| 0.3.0 | Error `Response` objects (status >= 400) are not cached | A cached 404 could be returned as 200 |
| 0.3.0 | Authenticated requests bypass the cache by default | Prevent cross-user response reuse |
| 0.3.0 | ETag is stable across processes and correctly quoted | `hash()` is randomized per process and the old header was invalid |
| 0.3.0 | `clear(key=...)` deletes only that key | It used to delete the whole prefix namespace |
| 0.3.0 | `clear("app:user")` does not delete `app:users` | Namespace matching requires the `:` boundary |
| 0.3.0 | `expire=None` means no expiration in `InMemoryBackend` | It used to expire almost immediately |
| 0.3.0 | `Cache-Control` never emits `max-age=None` or `max-age=-1` | Invalid headers |
| 0.3.0 | User payloads with a `_spec_type` key are not interpreted as internal metadata | The marker collided with user data |
| 0.3.0 | Non-JSON responses (streaming, file, redirect) are not cached blindly | Status/headers/body were lost or corrupted |
| 0.3.0 | A second `FastAPICache.init(...)` is not a silent no-op | Configuration was impossible to change |
These are bug fixes targeted for `0.3.0`. The error-response fix is implemented on `stable`;
the remaining rows are targeted for later pre-releases. Each one is documented in
[`MIGRATION.md`](MIGRATION.md) and covered by a regression test when implemented.

| Version | Change | Why | Status |
|---|---|---|---|
| 0.3.0 | Error `Response` objects (status >= 400) are not cached | A cached 404 could be returned as 200 | Implemented on `stable` |
| 0.3.0 | Authenticated requests bypass the cache by default | Prevent cross-user response reuse | Targeted |
| 0.3.0 | ETag is stable across processes and correctly quoted | `hash()` is randomized per process and the old header was invalid | Targeted |
| 0.3.0 | `clear(key=...)` deletes only that key | It used to delete the whole prefix namespace | Targeted |
| 0.3.0 | `clear("app:user")` does not delete `app:users` | Namespace matching requires the `:` boundary | Targeted |
| 0.3.0 | `expire=None` means no expiration in `InMemoryBackend` | It used to expire almost immediately | Targeted |
| 0.3.0 | `Cache-Control` never emits `max-age=None` or `max-age=-1` | Invalid headers | Targeted |
| 0.3.0 | User payloads with a `_spec_type` key are not interpreted as internal metadata | The marker collided with user data | Targeted |
| 0.3.0 | Non-JSON responses (streaming, file, redirect) are not cached blindly | Status/headers/body were lost or corrupted | Targeted |
| 0.3.0 | A second `FastAPICache.init(...)` is not a silent no-op | Configuration was impossible to change | Targeted |

## Cache data compatibility

Expand Down
15 changes: 9 additions & 6 deletions MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ normal success-path behavior. Bug fixes that change edge-case behavior are liste
are covered by regression tests. See [`COMPATIBILITY.md`](COMPATIBILITY.md) for the full
contract.

> **Status:** this guide describes the target `0.3.0` behavior. The current `0.3.0a0` alpha
> does not include these changes yet; they land in the `0.3.0` pre-releases. Check the
> installed version before relying on a behavior listed here.
> **Status:** this guide describes the target `0.3.0` behavior. The error-response fix is
> implemented on `stable`; the remaining changes are targeted for later `0.3.0` pre-releases.
> Check the installed version before relying on a behavior listed here.

## Who should migrate

Expand Down Expand Up @@ -76,9 +76,9 @@ python -c "from fastapi_cache import FastAPICache; print('ok')"

## Behavior changes in 0.3.0

These are intentional bug fixes targeted for `0.3.0`. The current alpha does not include
all of them yet. Each one will have a regression test and is listed here so you can decide
whether it affects you.
These are intentional bug fixes targeted for `0.3.0`. The error-response fix is implemented
on `stable`; the remaining changes are targeted for later pre-releases. Each one will have a
regression test and is listed here so you can decide whether it affects you.

| Change | Before (0.2.2) | After (0.3.0) |
|---|---|---|
Expand All @@ -93,6 +93,9 @@ whether it affects you.
| Non-JSON responses | Streaming/file/redirect could be cached incorrectly | Bypassed unless the coder supports them |
| Second `init` | Silent no-op | Reconfiguration is explicit and documented |

The error-response fix is implemented on `stable`. The remaining rows are targeted for later
`0.3.0` pre-releases.

**Action required:** if you were affected by cached error responses or by `clear(key=...)`,
flush the cache namespace after upgrading. If the ETag changes, clients may revalidate once.

Expand Down
1 change: 1 addition & 0 deletions changelog.d/2.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Avoid caching explicitly returned `Response` objects with status codes >= 400. Adapted from upstream PR #575 by RitiGrover.
11 changes: 11 additions & 0 deletions examples/in_memory/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,17 @@ async def cache_response_obj():
return JSONResponse({"a": 1})


error_ret = 0


@app.get("/error_response_obj")
@cache(namespace="test", expire=5)
async def error_response_obj(status_code: int = 404):
global error_ret
error_ret += 1
return JSONResponse({"error": "error response", "n": error_ret}, status_code=status_code)


class SomeClass:
def __init__(self, value):
self.value = value
Expand Down
2 changes: 2 additions & 0 deletions fastapi_cache/decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,8 @@ async def ensure_async_func(*args: P.args, **kwargs: P.kwargs) -> R:

if cached is None or (request is not None and request.headers.get("Cache-Control") == "no-cache") : # cache miss
result = await ensure_async_func(*args, **kwargs)
if isinstance(result, Response) and result.status_code >= 400:
return result
to_cache = coder.encode(result)

try:
Expand Down
65 changes: 8 additions & 57 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ requests = "*"
coverage = ">=6.5,<8.0"
httpx = "*"
tox = "^4.5.1"
towncrier = "^22.12.0"
towncrier = { version = ">=26,<27", python = ">=3.9" }

[tool.poetry.group.distributing]
optional = true
Expand Down
10 changes: 10 additions & 0 deletions tests/test_decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,16 @@ def test_non_get() -> None:
assert second.json()["value"] == first.json()["value"] + 1


def test_cache_error_response_obj_is_not_cached() -> None:
with TestClient(app) as client:
for status_code in (404, 500):
first = client.get("/error_response_obj", params={"status_code": status_code})
second = client.get("/error_response_obj", params={"status_code": status_code})
assert first.status_code == status_code
assert second.status_code == status_code
assert second.json()["n"] == first.json()["n"] + 1


def test_alternate_injected_namespace() -> None:
with TestClient(app) as client:
response = client.get("/namespaced_injection")
Expand Down
Loading