fastapi-cache-stable 0.3.0a1__tar.gz → 0.3.0a2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. {fastapi_cache_stable-0.3.0a1 → fastapi_cache_stable-0.3.0a2}/CHANGELOG.md +42 -0
  2. {fastapi_cache_stable-0.3.0a1 → fastapi_cache_stable-0.3.0a2}/COMPATIBILITY.md +64 -20
  3. {fastapi_cache_stable-0.3.0a1 → fastapi_cache_stable-0.3.0a2}/MIGRATION.md +197 -50
  4. {fastapi_cache_stable-0.3.0a1 → fastapi_cache_stable-0.3.0a2}/PKG-INFO +136 -14
  5. {fastapi_cache_stable-0.3.0a1 → fastapi_cache_stable-0.3.0a2}/README.md +135 -13
  6. {fastapi_cache_stable-0.3.0a1 → fastapi_cache_stable-0.3.0a2}/fastapi_cache/__init__.py +8 -0
  7. {fastapi_cache_stable-0.3.0a1 → fastapi_cache_stable-0.3.0a2}/fastapi_cache/backends/inmemory.py +18 -9
  8. {fastapi_cache_stable-0.3.0a1 → fastapi_cache_stable-0.3.0a2}/fastapi_cache/coder.py +51 -12
  9. fastapi_cache_stable-0.3.0a2/fastapi_cache/decorator.py +396 -0
  10. {fastapi_cache_stable-0.3.0a1 → fastapi_cache_stable-0.3.0a2}/pyproject.toml +1 -1
  11. fastapi_cache_stable-0.3.0a1/fastapi_cache/decorator.py +0 -233
  12. {fastapi_cache_stable-0.3.0a1 → fastapi_cache_stable-0.3.0a2}/FORK_ORIGIN.md +0 -0
  13. {fastapi_cache_stable-0.3.0a1 → fastapi_cache_stable-0.3.0a2}/LICENSE +0 -0
  14. {fastapi_cache_stable-0.3.0a1 → fastapi_cache_stable-0.3.0a2}/NOTICE +0 -0
  15. {fastapi_cache_stable-0.3.0a1 → fastapi_cache_stable-0.3.0a2}/SECURITY.md +0 -0
  16. {fastapi_cache_stable-0.3.0a1 → fastapi_cache_stable-0.3.0a2}/SUPPORT.md +0 -0
  17. {fastapi_cache_stable-0.3.0a1 → fastapi_cache_stable-0.3.0a2}/fastapi_cache/backends/__init__.py +0 -0
  18. {fastapi_cache_stable-0.3.0a1 → fastapi_cache_stable-0.3.0a2}/fastapi_cache/backends/dynamodb.py +0 -0
  19. {fastapi_cache_stable-0.3.0a1 → fastapi_cache_stable-0.3.0a2}/fastapi_cache/backends/memcached.py +0 -0
  20. {fastapi_cache_stable-0.3.0a1 → fastapi_cache_stable-0.3.0a2}/fastapi_cache/backends/redis.py +0 -0
  21. {fastapi_cache_stable-0.3.0a1 → fastapi_cache_stable-0.3.0a2}/fastapi_cache/key_builder.py +0 -0
  22. {fastapi_cache_stable-0.3.0a1 → fastapi_cache_stable-0.3.0a2}/fastapi_cache/py.typed +0 -0
  23. {fastapi_cache_stable-0.3.0a1 → fastapi_cache_stable-0.3.0a2}/fastapi_cache/types.py +0 -0
@@ -8,6 +8,48 @@ This project uses [*towncrier*](https://towncrier.readthedocs.io/) and the chang
8
8
 
9
9
  <!-- towncrier release notes start -->
10
10
 
11
+ ## [0.3.0a2](https://github.com/agustin18/fastapi-cache/tree/v0.3.0a2) - 2026-11-14
12
+
13
+ ### Bugfixes
14
+
15
+ - Bypass the cache for requests with a non-empty `Authorization` or `Cookie` header by
16
+ default. Add `cache_authenticated=True` to opt in with an identity-aware `key_builder`;
17
+ opting in with the default key builder raises `ValueError` for authenticated requests.
18
+ Backend error logs now report only the endpoint, namespace, and exception type; they no
19
+ longer include the cache key, exception message, or traceback.
20
+ Clear or rotate the cache namespace when upgrading from versions that cached authenticated
21
+ responses. [#12](https://github.com/agustin18/fastapi-cache/issues/12)
22
+ - InMemory backend: `expire=None` now means no expiration instead of immediate expiry, and each
23
+ backend instance has its own store and lock. Existing process-local entries are not shared
24
+ between instances; use a shared backend for cross-process caching. [#13](https://github.com/agustin18/fastapi-cache/issues/13)
25
+ - Emit `Cache-Control: max-age` only when the effective expiry is valid and non-negative.
26
+ `expire=None` and no-expiration InMemory hits no longer produce `max-age=None` or
27
+ `max-age=-1`; `ETag` and the cache-status header are still emitted. `expire=0` keeps the
28
+ legacy fallback to the global `expire` value. [#14](https://github.com/agustin18/fastapi-cache/issues/14)
29
+ - Use a stable SHA-256 digest for the ETag and emit it as a quoted weak validator
30
+ (`W/"<digest>"`). `If-None-Match` now uses weak comparison, supports comma-separated lists
31
+ and `*`, and is evaluated on both cache hits and misses, including after
32
+ `Cache-Control: no-cache`. Malformed entity-tags are ignored. The ETag value changes once
33
+ when upgrading; clients revalidate and receive the new value. [#15](https://github.com/agustin18/fastapi-cache/issues/15)
34
+ - Namespace the internal `_spec_type` marker as `__fastapi_cache_spec_type__` so user payloads
35
+ with `_spec_type` are preserved. `JsonCoder` now caches only simple `JSONResponse` objects
36
+ (status `200`, `application/json`, no custom headers, no background task) and bypasses other
37
+ non-JSON responses (`StreamingResponse`, `FileResponse`, `RedirectResponse`, plain `Response`,
38
+ templates). Responses with `Set-Cookie`, `Cache-Control: no-store`/`private`, or a background
39
+ task are never cached, regardless of the coder. The injected `response` object is also
40
+ checked before a cache read and before writing; cookies, `Cache-Control: no-store`/`private`,
41
+ background tasks, non-`200` statuses, and custom headers bypass the cache. `PickleCoder` caches serializable response
42
+ objects it can reproduce faithfully and bypasses streaming, file, and template responses. Old
43
+ cache entries written with `_spec_type` are treated as user data; flush the namespace if you
44
+ cache `datetime`/`date`/`Decimal` values. [#16](https://github.com/agustin18/fastapi-cache/issues/16)
45
+
46
+ ### Improved Documentation
47
+
48
+ - Document the published `0.3.0a1` release and pin the alpha install commands. [#11](https://github.com/agustin18/fastapi-cache/issues/11)
49
+ - Document the `0.3.0a2` release status, pin the alpha install commands, and record the tested
50
+ Redis/redis-py compatibility. The auth/privacy, InMemory, `Cache-Control`, ETag,
51
+ `_spec_type`, and response-bypass fixes are now available in `0.3.0a2`. [#17](https://github.com/agustin18/fastapi-cache/issues/17)
52
+
11
53
  ## [0.3.0a1](https://github.com/agustin18/fastapi-cache/tree/v0.3.0a1) - 2026-11-14
12
54
 
13
55
  ### Bugfixes
@@ -12,6 +12,12 @@
12
12
  miss calls the endpoint, cache hit returns the cached value, and the cache status header
13
13
  reports `MISS`/`HIT`.
14
14
  - Existing `@cache(...)` and `FastAPICache.init(...)` calls keep working without code changes.
15
+ - Authenticated requests bypass the cache by default. This is an intentional privacy behavior
16
+ change; authenticated endpoints must opt in with `cache_authenticated=True` and an
17
+ identity-aware `key_builder` to keep caching.
18
+ - `InMemoryBackend` instances are isolated: each owns its store and lock. `expire=None` means
19
+ no expiration. InMemory remains process-local; use a shared backend for cross-process
20
+ caching.
15
21
  - Existing custom backends, coders and key builders that implement the documented protocols
16
22
  keep working.
17
23
  - Migration from `fastapi-cache2` does not require application code changes for valid legacy
@@ -52,6 +58,7 @@ FastAPICache.init(
52
58
  key_builder=default_key_builder,
53
59
  cache_status_header="X-FastAPI-Cache",
54
60
  enable=True,
61
+ cache_authenticated=False,
55
62
  )
56
63
  FastAPICache.clear(namespace=None, key=None)
57
64
  FastAPICache.reset()
@@ -62,6 +69,7 @@ FastAPICache.get_coder()
62
69
  FastAPICache.get_key_builder()
63
70
  FastAPICache.get_cache_status_header()
64
71
  FastAPICache.get_enable()
72
+ FastAPICache.get_cache_authenticated()
65
73
  ```
66
74
 
67
75
  ### `@cache(...)`
@@ -73,6 +81,7 @@ cache(
73
81
  key_builder=None,
74
82
  namespace="",
75
83
  injected_dependency_namespace="__fastapi_cache",
84
+ cache_authenticated=None,
76
85
  )
77
86
  ```
78
87
 
@@ -102,6 +111,7 @@ def __call__(
102
111
  ### `Coder` protocol
103
112
 
104
113
  ```python
114
+ classmethod can_encode(value) -> bool
105
115
  classmethod encode(value) -> bytes
106
116
  classmethod decode(value: bytes) -> Any
107
117
  classmethod decode_as_type(value: bytes, *, type_) -> Any
@@ -145,12 +155,12 @@ Status definitions:
145
155
  | `Response`/`JSONResponse` annotations | Legacy decoded behavior | No Pydantic schema generation; cache hits keep working |
146
156
  | Redis standalone | Verified for clear semantics | Redis 7 service in CI with redis-py 4.6.0; key-only clear and namespace boundary tested. redis-py 5/6 are not supported by the current `^4.2.0rc1` constraint and are untested |
147
157
  | Redis Cluster | Unsupported for namespace clear | Key-only clear is supported; namespace clear raises `NotImplementedError`; no complete namespace clearing |
148
- | InMemory | Verified for basic operations and clear semantics | Unit tests; instance isolation is targeted for 0.3.0; the current implementation shares state between instances; no size cap yet |
158
+ | InMemory | Verified for basic operations, clear semantics, `expire=None` and instance isolation | Unit tests; each instance owns its store and lock; no size cap yet |
149
159
  | Memcached | Experimental | No full `clear`/TTL parity; `clear` raises `NotImplementedError` |
150
160
  | DynamoDB | Experimental | `clear` raises `NotImplementedError`; the client cleanup issue remains open and is targeted for a future fix |
151
161
  | Import `fastapi_cache` | Verified | Covered by compatibility tests |
152
162
 
153
- > Redis results in `0.3.0a1` cover Redis 7 with redis-py 4.6.0. Other client or server
163
+ > Redis results in `0.3.0a2` cover Redis 7 with redis-py 4.6.0. Other client or server
154
164
  > versions are not verified; do not infer support from the Redis 7 job alone.
155
165
 
156
166
  ### `0.3.0a1` status
@@ -158,9 +168,25 @@ Status definitions:
158
168
  Implemented: error responses, opt-in `TypedJsonCoder`, `clear()` key/namespace semantics,
159
169
  Redis Cluster namespace `NotImplementedError`, and the legacy compatibility matrix.
160
170
 
161
- Targeted for later pre-releases: auth/privacy defaults, stable ETag, InMemory expiry and
162
- instance isolation, `Cache-Control`/`max-age`, non-JSON bypass, `_spec_type` collision
163
- handling, explicit re-`init()`, and the Redis client/server matrix.
171
+ ### `0.3.0a2` status
172
+
173
+ Implemented in `0.3.0a2`: authenticated requests bypass the
174
+ cache by default; opt-in with `cache_authenticated=True` and an identity-aware `key_builder`.
175
+ Opting in with the default key builder raises `ValueError` for authenticated requests.
176
+ `InMemoryBackend` instances are isolated, and `expire=None` means no expiration. The
177
+ decorator emits `Cache-Control: max-age` only for valid, non-negative expiry values; it
178
+ omits `max-age` for `expire=None` and no-expiration hits. `expire=0` keeps the legacy
179
+ fallback to the global `expire` value. ETags are quoted weak validators derived from a
180
+ stable SHA-256 digest; `If-None-Match` uses weak comparison, supports lists and `*`, is
181
+ evaluated on hits and misses, and ignores malformed entity-tags. `_spec_type` user payloads
182
+ are preserved via a namespaced internal marker. `JsonCoder` caches only simple `200`
183
+ `application/json` `JSONResponse` objects; other responses are bypassed unless the coder's
184
+ `can_encode` supports them. Responses with `Set-Cookie`, `Cache-Control: no-store/private`,
185
+ or a background task are never cached. The injected `response` object is checked before a
186
+ cache read and before a write; those directives, a non-`200` status, or any header other than
187
+ the automatic `content-length` bypass the cache for dict/list returns.
188
+
189
+ Targeted for later pre-releases: explicit re-`init()` and the Redis client/server matrix.
164
190
 
165
191
  ### Clear semantics
166
192
 
@@ -178,39 +204,57 @@ handling, explicit re-`init()`, and the Redis client/server matrix.
178
204
  ## Intentional behavior changes
179
205
 
180
206
  These are bug fixes targeted for `0.3.0`. The error-response, typed-decode and
181
- clear-semantics fixes are implemented in `0.3.0a1`; the remaining rows are targeted for
182
- later pre-releases. Each one is documented in [`MIGRATION.md`](MIGRATION.md) and covered by
183
- a regression test when implemented.
207
+ clear-semantics fixes are implemented in `0.3.0a1`; the auth/privacy, InMemory,
208
+ `Cache-Control`, ETag, `_spec_type` and response-caching fixes are implemented in `0.3.0a2`;
209
+ the second-`init` row is targeted for later pre-releases. Each one is documented in [`MIGRATION.md`](MIGRATION.md) and covered by a
210
+ regression test when implemented.
184
211
 
185
212
  | Version | Change | Why | Status |
186
213
  |---|---|---|---|
187
- | 0.3.0 | Error `Response` objects (status >= 400) are not cached | A cached 404 could be returned as 200 | Implemented on `stable` |
188
- | 0.3.0 | Opt-in `TypedJsonCoder` decodes cached JSON into the annotated return type on Pydantic v2 | Default `JsonCoder` and Pydantic v1 keep the legacy decoded behavior; `TypedJsonCoder` propagates validation errors | Implemented on `stable` |
189
- | 0.3.0 | Authenticated requests bypass the cache by default | Prevent cross-user response reuse | Targeted |
190
- | 0.3.0 | ETag is stable across processes and correctly quoted | `hash()` is randomized per process and the old header was invalid | Targeted |
191
- | 0.3.0 | `clear(key=...)` deletes only that key | It used to delete the whole prefix namespace | Implemented on `stable` |
192
- | 0.3.0 | `clear("app:user")` does not delete `app:users` | Namespace matching requires the `:` boundary | Implemented on `stable` |
193
- | 0.3.0 | Redis Cluster namespace clear raises `NotImplementedError` | Partial/unsafe clearing was not reliable | Implemented on `stable` |
194
- | 0.3.0 | `expire=None` means no expiration in `InMemoryBackend` | It used to expire almost immediately | Targeted |
195
- | 0.3.0 | `Cache-Control` never emits `max-age=None` or `max-age=-1` | Invalid headers | Targeted |
196
- | 0.3.0 | User payloads with a `_spec_type` key are not interpreted as internal metadata | The marker collided with user data | Targeted |
197
- | 0.3.0 | Non-JSON responses (streaming, file, redirect) are not cached blindly | Status/headers/body were lost or corrupted | Targeted |
214
+ | 0.3.0 | Error `Response` objects (status >= 400) are not cached | A cached 404 could be returned as 200 | Implemented in `0.3.0a1` |
215
+ | 0.3.0 | Opt-in `TypedJsonCoder` decodes cached JSON into the annotated return type on Pydantic v2 | Default `JsonCoder` and Pydantic v1 keep the legacy decoded behavior; `TypedJsonCoder` propagates validation errors | Implemented in `0.3.0a1` |
216
+ | 0.3.0 | Authenticated requests bypass the cache by default | Prevent cross-user response reuse | Implemented in `0.3.0a2` |
217
+ | 0.3.0 | ETag is stable across processes and correctly quoted | `hash()` is randomized per process and the old header was invalid | Implemented in `0.3.0a2` |
218
+ | 0.3.0 | `clear(key=...)` deletes only that key | It used to delete the whole prefix namespace | Implemented in `0.3.0a1` |
219
+ | 0.3.0 | `clear("app:user")` does not delete `app:users` | Namespace matching requires the `:` boundary | Implemented in `0.3.0a1` |
220
+ | 0.3.0 | Redis Cluster namespace clear raises `NotImplementedError` | Partial/unsafe clearing was not reliable | Implemented in `0.3.0a1` |
221
+ | 0.3.0 | `expire=None` means no expiration in `InMemoryBackend` | It used to expire almost immediately | Implemented in `0.3.0a2` |
222
+ | 0.3.0 | `InMemoryBackend` instances do not share state | The class-level store leaked entries between instances | Implemented in `0.3.0a2` |
223
+ | 0.3.0 | `Cache-Control` never emits `max-age=None` or `max-age=-1` | Invalid headers | Implemented in `0.3.0a2` |
224
+ | 0.3.0 | User payloads with a `_spec_type` key are not interpreted as internal metadata | The marker collided with user data | Implemented in `0.3.0a2` |
225
+ | 0.3.0 | Only simple `JSONResponse` objects are cached by `JsonCoder`; other responses bypass | Status/headers/body were lost or corrupted | Implemented in `0.3.0a2` |
226
+ | 0.3.0 | Responses with `Set-Cookie`, `Cache-Control: no-store/private`, or a background task are never cached | Cookies and private data could be replayed to other clients | Implemented in `0.3.0a2` |
227
+ | 0.3.0 | Injected `response` metadata is checked before cache reads and writes | Dict/list responses could cache cookies, private data, custom statuses, or custom headers | Implemented in `0.3.0a2` |
198
228
  | 0.3.0 | A second `FastAPICache.init(...)` is not a silent no-op | Configuration was impossible to change | Targeted |
199
229
 
200
230
  ## Cache data compatibility
201
231
 
202
- - **ETag:** the value changes once. Clients may revalidate after upgrading.
232
+ - **ETag:** the value changes once. The new value is a stable SHA-256 digest; clients may
233
+ revalidate after upgrading.
203
234
  - **Key format:** if a release changes the default key format, old entries become
204
235
  unreachable. Flush the cache namespace after upgrading.
205
236
  - **Error responses:** old cached error entries may remain until their TTL expires. Flush
206
237
  the cache namespace if you were affected.
238
+ - **Authenticated responses:** entries written by versions that cached authenticated requests
239
+ under the default key may remain. Clear or rotate the cache namespace before deploying the
240
+ bypass, including all instances/workers and persistent Redis caches. The bypass is not
241
+ retroactive.
242
+ - **InMemory:** data is process-local and is lost on restart. Instances no longer share a
243
+ store; a new backend after `FastAPICache.reset()` starts empty. No data-format migration.
207
244
  - **Pydantic/dataclass values:** old entries encoded as plain JSON still decode; the
208
245
  annotated type is restored on read. No flush required for this fix alone.
246
+ - **`_spec_type`:** the internal marker changed to `__fastapi_cache_spec_type__`. Old entries
247
+ written with `_spec_type` are treated as user data; flush the namespace if you cache
248
+ `datetime`/`date`/`Decimal` values.
209
249
 
210
250
  ## How compatibility is tested
211
251
 
212
252
  - API signature tests for the public names above.
213
253
  - Characterization tests for the normal GET success path.
254
+ - Auth/privacy tests for default bypass, opt-in isolation, backend non-access, and legacy
255
+ cache-entry invalidation.
256
+ - InMemory tests for `expire=None`, instance isolation, clear isolation, and decorator
257
+ default-expire behavior.
214
258
  - Regression tests for every behavior change.
215
259
  - CI tests Python 3.10–3.13 with resolver-selected FastAPI and Pydantic versions.
216
260
  - A `legacy-compat` job tests Python 3.8/3.9 with FastAPI 0.111.1 and Pydantic 1.10.27/2.8.2,
@@ -14,11 +14,13 @@ normal success-path behavior. Bug fixes that change edge-case behavior are liste
14
14
  are covered by regression tests. See [`COMPATIBILITY.md`](COMPATIBILITY.md) for the full
15
15
  contract.
16
16
 
17
- > **Status:** this guide describes `0.3.0a1` and the target `0.3.0` behavior. `0.3.0a1`
18
- > implements the error-response fix, the opt-in `TypedJsonCoder`, the `clear()` fixes and the
19
- > legacy compatibility matrix. Auth/privacy, ETag, InMemory expiry/isolation, non-JSON bypass,
20
- > `_spec_type` and second-`init` fixes are targeted for later `0.3.0` pre-releases. Check the
21
- > installed version before relying on a behavior listed here.
17
+ > **Status:** this guide describes `0.3.0a2` and the target `0.3.0` behavior. `0.3.0a2`
18
+ > implements the error-response fix, the opt-in `TypedJsonCoder`, the `clear()` fixes, the
19
+ > legacy compatibility matrix, the auth/privacy bypass, the InMemory
20
+ > `expire=None`/instance-isolation fixes, the `Cache-Control` fix, the stable ETag, the
21
+ > `_spec_type` namespacing and the non-JSON response bypass. The second-`init` fix is targeted
22
+ > for a later `0.3.0` pre-release. Check the installed version before relying on a behavior
23
+ > listed here.
22
24
 
23
25
  ## Who should migrate
24
26
 
@@ -50,8 +52,7 @@ for Pydantic v1 models and annotations that cannot be represented by a Pydantic
50
52
  ## Who should not migrate yet
51
53
 
52
54
  - You need full Memcached or DynamoDB parity. They are experimental in `0.3.x`.
53
- - You need the auth/privacy, ETag, InMemory expiry/isolation, non-JSON bypass, `_spec_type`
54
- or second-`init` fixes; they are targeted for later `0.3.0` pre-releases.
55
+ - You need the second-`init` fix; it is targeted for a later `0.3.0` pre-release.
55
56
  - You use Redis Cluster and need complete namespace clearing.
56
57
  - You need typed restoration on Pydantic v1; the legacy decoded behavior is preserved instead.
57
58
  Pydantic v1 is end-of-life; plan an upgrade to Pydantic v2 for typed restoration and
@@ -61,11 +62,13 @@ for Pydantic v1 models and annotations that cannot be represented by a Pydantic
61
62
 
62
63
  ## Install
63
64
 
65
+ `0.3.0a2` is a pre-release. Install the exact version:
66
+
64
67
  ```sh
65
68
  pip uninstall -y fastapi-cache2
66
- pip install fastapi-cache-stable
69
+ pip install "fastapi-cache-stable==0.3.0a2"
67
70
  # with extras:
68
- pip install "fastapi-cache-stable[redis]"
71
+ pip install "fastapi-cache-stable[redis]==0.3.0a2"
69
72
  ```
70
73
 
71
74
  Do **not** install both distributions in the same environment: they provide the same
@@ -80,15 +83,16 @@ python -c "from fastapi_cache import FastAPICache; print('ok')"
80
83
 
81
84
  ### Alpha installation from TestPyPI
82
85
 
83
- `0.3.0a1` will be published to TestPyPI first; it is not published yet. TestPyPI is a
84
- separate index and may not have all dependencies. To verify the exact artifact uploaded to
85
- TestPyPI, download it from that index and install the local wheel:
86
+ `0.3.0a2` is the next pre-release; it will be published to TestPyPI and PyPI. The previous
87
+ `0.3.0a1` is already published. TestPyPI is a separate index and may not have all
88
+ dependencies. To verify the exact artifact uploaded to TestPyPI, download it from that index
89
+ and install the local wheel:
86
90
 
87
91
  ```sh
88
92
  python -m pip download --no-deps --only-binary=:all: \
89
93
  --index-url https://test.pypi.org/simple/ \
90
94
  -d testpypi-dist \
91
- "fastapi-cache-stable==0.3.0a1"
95
+ "fastapi-cache-stable==0.3.0a2"
92
96
 
93
97
  python -m pip install testpypi-dist/*.whl
94
98
  python -m pip check
@@ -96,8 +100,7 @@ python -c "import fastapi_cache; print(fastapi_cache.__version__)"
96
100
  ```
97
101
 
98
102
  Dependencies are resolved from PyPI by the normal install of the wheel. TestPyPI is for
99
- validating the distribution, not for production. The same version can be published to PyPI
100
- later.
103
+ validating the distribution, not for production. The same version is also published to PyPI.
101
104
 
102
105
  ## Compatibility matrix
103
106
 
@@ -117,39 +120,175 @@ later.
117
120
  | `Response`/`JSONResponse` annotations | Legacy decoded behavior | No Pydantic schema generation; cache hits keep working |
118
121
  | Redis standalone | Verified for clear semantics | Redis 7 service in CI with redis-py 4.6.0; key-only clear and namespace boundary tested. redis-py 5/6 are not supported by the current `^4.2.0rc1` constraint and are untested |
119
122
  | Redis Cluster | Unsupported | `clear` limitations documented; no complete namespace clearing |
120
- | InMemory | Verified for basic operations | Unit tests; instance isolation is targeted for 0.3.0; the current implementation shares state between instances; no size cap yet |
123
+ | InMemory | Verified for basic operations, clear semantics, `expire=None` and instance isolation | Unit tests; each instance owns its store and lock; no size cap yet |
121
124
  | Memcached | Experimental | No full `clear`/TTL parity |
122
125
  | DynamoDB | Experimental | `clear` is not implemented; the client cleanup issue remains open and is targeted for a future fix |
123
126
  | Import `fastapi_cache` | Verified | Covered by compatibility tests |
124
127
 
125
128
  > The Redis integration job installs the resolver-selected `redis` version from the project
126
129
  > constraint (`^4.2.0rc1`), currently 4.6.0, and runs against a Redis 7 service. Other client
127
- > or server versions are not verified in `0.3.0a1`.
130
+ > or server versions are not verified in `0.3.0a2`.
128
131
 
129
132
  ## Behavior changes in 0.3.0
130
133
 
131
134
  These are intentional bug fixes targeted for `0.3.0`. `0.3.0a1` implements the error-response,
132
- typed-decode and clear-semantics fixes; the remaining changes are targeted for later
133
- pre-releases. Each one will have a regression test and is listed here so you can decide
134
- whether it affects you.
135
+ typed-decode and clear-semantics fixes; `0.3.0a2` implements the auth/privacy bypass, the
136
+ InMemory, `Cache-Control`, ETag, `_spec_type` and non-JSON fixes. The remaining changes are
137
+ targeted for later pre-releases. Each one has a regression test and is listed here so you can
138
+ decide whether it affects you.
135
139
 
136
140
  | Change | Before (0.2.2) | After (0.3.0) | Status |
137
141
  |---|---|---|---|
138
142
  | Error responses | A cached 404 could be returned as 200 | Responses with status >= 400 are not cached | Implemented in 0.3.0a1 |
139
143
  | Typed JSON decode | Cache hits returned plain dicts/lists | Opt-in `TypedJsonCoder` on Pydantic v2; default `JsonCoder`, Pydantic v1 and unsupported annotations keep the legacy decoded behavior; validation errors propagate | Implemented in 0.3.0a1 |
140
- | Authenticated requests | Two users could share a cache key | Requests with `Authorization`/`Cookie`/session bypass the cache by default; opt-in with a safe `key_builder` | Targeted |
141
- | ETag | `hash()` changes per process; header unquoted | Stable digest, quoted weak ETag, correct `If-None-Match` | Targeted |
144
+ | Authenticated requests | Two users could share a cache key | Requests with `Authorization`/`Cookie`/session bypass the cache by default; opt-in with `cache_authenticated=True` and a safe `key_builder` | Implemented in 0.3.0a2 |
145
+ | ETag | `hash()` changes per process; header unquoted | Stable SHA-256 digest, quoted weak ETag, weak `If-None-Match` comparison including lists and `*` | Implemented in 0.3.0a2 |
142
146
  | `clear(key=...)` | Deleted the whole prefix namespace | Deletes only that key; pass the full key | Implemented in 0.3.0a1 |
143
147
  | Namespace boundary | `clear("app:user")` also deleted `app:users` | Requires the `:` boundary | Implemented in 0.3.0a1 |
144
148
  | Redis Cluster namespace clear | Partial/unsafe clearing | Raises `NotImplementedError`; use key-only clear or flush out of band | Implemented in 0.3.0a1 |
145
- | `expire=None` in InMemory | Expired almost immediately | Means no expiration | Targeted |
146
- | `Cache-Control` | Could emit `max-age=None` or `max-age=-1` | Only valid values | Targeted |
147
- | `_spec_type` | User payloads with that key raised `TypeError` | Internal marker is namespaced; user data is preserved | Targeted |
148
- | Non-JSON responses | Streaming/file/redirect could be cached incorrectly | Bypassed unless the coder supports them | Targeted |
149
+ | `expire=None` in InMemory | Expired almost immediately | Means no expiration; `get_with_ttl` returns `-1` | Implemented in 0.3.0a2 |
150
+ | `Cache-Control` | Could emit `max-age=None` or `max-age=-1` | Only valid values; `max-age` is omitted when no valid expiry exists | Implemented in 0.3.0a2 |
151
+ | `_spec_type` | User payloads with that key raised `TypeError` | Internal marker is namespaced as `__fastapi_cache_spec_type__`; user data is preserved | Implemented in 0.3.0a2 |
152
+ | Response caching | Streaming/file/redirect and metadata-bearing `JSONResponse` could be cached incorrectly | `JsonCoder` caches only simple `200`/`application/json` `JSONResponse`; other responses bypass; `PickleCoder` bypasses streaming/file/template; `Set-Cookie`, `Cache-Control: no-store/private` and background tasks never cache | Implemented in 0.3.0a2 |
149
153
  | Second `init` | Silent no-op | Reconfiguration is explicit and documented | Targeted |
150
154
 
151
155
  The error-response, typed-decode and clear-semantics fixes are implemented in `0.3.0a1`.
152
- The remaining rows are targeted for later `0.3.0` pre-releases.
156
+ The auth/privacy bypass, InMemory, `Cache-Control`, ETag, `_spec_type` and non-JSON fixes are
157
+ implemented in `0.3.0a2`. The second-`init` row is targeted for a later `0.3.0` pre-release.
158
+
159
+ ### Authenticated requests
160
+
161
+ `0.3.0a1` caches requests with `Authorization`/`Cookie` using the default key. `0.3.0a2`
162
+ bypasses the cache for requests with a non-empty
163
+ `Authorization` or `Cookie` header. Public requests keep caching. Functions decorated
164
+ without a `Request` parameter have no HTTP identity context and keep using the cache.
165
+
166
+ To cache authenticated responses, opt in explicitly and provide a key builder that includes
167
+ the identity. The key builder must include every dimension that affects the response: token,
168
+ session, tenant, permissions, and any other validated principal state. Prefer the principal
169
+ your application already validated over raw headers. Do not put credentials in plaintext in
170
+ keys or logs; use HMAC-SHA256 with an application secret.
171
+
172
+ ```python
173
+ import hashlib
174
+ import hmac
175
+ import os
176
+
177
+ from fastapi_cache import FastAPICache
178
+ from fastapi_cache.decorator import cache
179
+
180
+ CACHE_KEY_SECRET = os.environ["CACHE_KEY_SECRET"].encode()
181
+
182
+
183
+ def identity_key_builder(
184
+ func,
185
+ namespace: str = "",
186
+ *,
187
+ request=None,
188
+ response=None,
189
+ args,
190
+ kwargs,
191
+ ):
192
+ identity = ""
193
+ if request is not None:
194
+ identity = "|".join(
195
+ [
196
+ request.headers.get("Authorization", ""),
197
+ request.headers.get("Cookie", ""),
198
+ ]
199
+ )
200
+ key_material = f"{identity}|{args}|{kwargs}"
201
+ digest = hmac.new(
202
+ CACHE_KEY_SECRET,
203
+ key_material.encode(),
204
+ hashlib.sha256,
205
+ ).hexdigest()
206
+ return f"{namespace}:{func.__module__}:{func.__name__}:{digest}"
207
+
208
+
209
+ FastAPICache.init(backend, cache_authenticated=True, key_builder=identity_key_builder)
210
+
211
+
212
+ @app.get("/me")
213
+ @cache(expire=60)
214
+ async def me(request):
215
+ ...
216
+ ```
217
+
218
+ If `cache_authenticated=True` is used with the default key builder, an authenticated request
219
+ raises `ValueError` before the cache is accessed. A custom key builder alone does not opt in;
220
+ the explicit flag is required.
221
+
222
+ The automatic bypass only detects `Authorization` and `Cookie`. Applications that use
223
+ `X-API-Key`, proxy-injected headers, `request.state`, or internal dependencies must review
224
+ their cache strategy. `cache_authenticated=True` does not make an unsafe key builder safe.
225
+
226
+ This fix protects the application cache. It does not configure CDN, reverse-proxy, or browser
227
+ caching.
228
+
229
+ **Action required when upgrading from `0.3.0a1` or earlier:** entries written for
230
+ authenticated requests may remain under the old default key. The bypass only affects new
231
+ requests. Before deploying, clear or rotate the cache namespace, including all
232
+ instances/workers and persistent Redis caches. A public request could otherwise read an old
233
+ private entry.
234
+
235
+ ### InMemory expiration and isolation
236
+
237
+ In `0.3.0a1`, `expire=None` expires almost immediately, and `_store`/`_lock` are shared across
238
+ all `InMemoryBackend` instances. In `0.3.0a2`:
239
+
240
+ - `expire=None` means no expiration; `get_with_ttl` returns `-1`, matching Redis/DynamoDB.
241
+ - Each backend instance owns its store and lock. A new backend after `FastAPICache.reset()`
242
+ starts empty. Do not share one instance across event loops or threads; use one instance per
243
+ loop/thread. Subclasses that override `__init__()` must call `super().__init__()`.
244
+ - `expire=0` keeps the legacy `or` fallback: it uses the global `expire` value. It is not
245
+ a new "no expiration" or "expire immediately" switch.
246
+ - `FastAPICache.reset()` resets configuration, not cache data.
247
+ - InMemory remains process-local; use Redis/Memcached for cross-process sharing.
248
+
249
+ The decorator now omits `max-age` when the effective expiry is unknown (`expire=None`) or
250
+ negative, including no-expiration InMemory hits (`ttl=-1`). `ETag` and the cache-status
251
+ header are still emitted. This is implemented in `0.3.0a2`.
252
+
253
+ No data-format migration is needed: InMemory data is process-local and is lost on restart.
254
+ If you relied on class-level sharing between instances, use a shared backend instead.
255
+
256
+ ### ETag and conditional requests
257
+
258
+ ETags are quoted weak validators derived from a stable SHA-256 digest of the cached
259
+ representation: `W/"<hex>"`. The value is stable across worker processes. `If-None-Match`
260
+ uses weak comparison, so `W/"<digest>"` and `"<digest>"` both match; comma-separated lists
261
+ and `*` are supported. Conditional requests are evaluated against the generated
262
+ representation on both cache hits and misses, including after `Cache-Control: no-cache`.
263
+ Malformed entity-tags are ignored. A matching conditional GET returns `304 Not Modified`
264
+ with the ETag and cache-status headers and no body. The ETag value changes once when
265
+ upgrading from `0.3.0a1`/0.2.2 because the format changed; clients revalidate and receive
266
+ the new value.
267
+
268
+ ### `_spec_type` and user payloads
269
+
270
+ The internal marker is now `__fastapi_cache_spec_type__` instead of `_spec_type`. User
271
+ payloads that contain `_spec_type` are preserved as normal data. The decoder only interprets
272
+ the namespaced marker when the object contains exactly the marker and `val`; any other shape
273
+ is returned unchanged. Old cached entries written with the `_spec_type` marker are no longer
274
+ converted to `datetime`/`date`/`Decimal`; flush the cache namespace if you rely on those
275
+ conversions.
276
+
277
+ ### Non-JSON responses
278
+
279
+ `JsonCoder` only caches simple `JSONResponse` objects: status `200`, media type
280
+ `application/json`, no custom headers, and no background task. `StreamingResponse`,
281
+ `FileResponse`, `RedirectResponse`, plain `Response`, template responses, and `JSONResponse`
282
+ objects with additional status/header metadata are returned directly and are not cached.
283
+ Custom coders can override `Coder.can_encode()` to opt in; `PickleCoder` caches
284
+ `JSONResponse`, plain `Response`, and `RedirectResponse` objects, and bypasses streaming,
285
+ file, and template responses. Responses with `Set-Cookie`, `Cache-Control: no-store` or
286
+ `Cache-Control: private`, or a background task are never cached, regardless of the coder.
287
+ A plain `Response` with a JSON media type is bypassed unless it is a `JSONResponse` or a
288
+ custom coder supports it. The injected `response` object is checked before a cache read and
289
+ before a write; `Set-Cookie`, `Cache-Control: no-store`/`private`, a background task, a
290
+ non-`200` status, or any header other than the automatic `content-length` bypasses the cache
291
+ for dict/list returns.
153
292
 
154
293
  **Action required:** if you were affected by cached error responses or by `clear(key=...)`,
155
294
  flush the cache namespace after upgrading. If you relied on `clear(key=...)` clearing the whole
@@ -157,7 +296,8 @@ prefix, switch to `clear()` or `clear(namespace=...)`. If you relied on `clear("
157
296
  deleting `app:users`, use the exact namespace. Redis Cluster users must use key-only clear or
158
297
  flush the database out of band. Namespace clear is best-effort and not atomic. `clear()` is an
159
298
  administrative operation; do not expose it to untrusted input. If the ETag changes, clients may
160
- revalidate once.
299
+ revalidate once. If you previously cached responses with cookies or private data, flush the
300
+ namespace as well.
161
301
 
162
302
  ## Step by step
163
303
 
@@ -169,10 +309,13 @@ revalidate once.
169
309
  `fastapi-cache-stable`, and verify `fastapi_cache.__version__`.
170
310
  4. **Configure once.** Call `FastAPICache.init(...)` once during startup. Define prefix,
171
311
  expire, coder and key builder. Review authenticated endpoints.
172
- 5. **Run tests.** Expect changes in error responses and `clear()` in `0.3.0a1`; ETag and
173
- auth changes are targeted for later pre-releases. Update asserts with the documented
174
- behavior.
175
- 6. **Flush if needed.** If the key format or ETag changed, clear the old namespace.
312
+ 5. **Run tests.** Expect changes in error responses and `clear()` in `0.3.0a1`; in `0.3.0a2`,
313
+ authenticated requests bypass the cache, InMemory expiry/isolation changes apply, the ETag
314
+ format changes once, `_spec_type` user payloads are preserved, and non-JSON responses
315
+ bypass the cache. The second-`init` change remains targeted. Update asserts with the
316
+ documented behavior.
317
+ 6. **Flush if needed.** If the key format or ETag changed, clear the old namespace. For the
318
+ auth bypass, clearing or rotating the namespace is required, not optional.
176
319
  7. **Observe.** Compare HIT/MISS, latency, errors and memory with your baseline.
177
320
  8. **Roll back if needed.** See below.
178
321
 
@@ -193,12 +336,14 @@ restore cache entries written with the new format; they are regenerated.
193
336
  **Can I install both packages?** No, not in the same environment.
194
337
  **What happens to my cached data?** If the key format or ETag changed, entries are
195
338
  regenerated. Flush the namespace if you were affected by an error-response or clear bug.
196
- **Is `0.3.0a1` production-ready?** No. It is an alpha for migration and distribution testing.
197
- **What is implemented in `0.3.0a1`?** Error responses are not cached, opt-in `TypedJsonCoder`
198
- for Pydantic v2, `clear()` key/namespace semantics, and the legacy compatibility matrix.
199
- **What is still missing?** Auth/privacy defaults, stable ETag, InMemory expiry/isolation,
200
- non-JSON bypass, `_spec_type` collision handling and explicit re-`init()` are targeted for
201
- later `0.3.0` pre-releases.
339
+ **Is `0.3.0a2` production-ready?** No. It is an alpha for migration and distribution testing.
340
+ **What is implemented in `0.3.0a2`?** Error responses are not cached, opt-in `TypedJsonCoder`
341
+ for Pydantic v2, `clear()` key/namespace semantics, the legacy compatibility matrix, the
342
+ auth/privacy bypass, the InMemory fixes, `Cache-Control`, the stable ETag, `_spec_type`
343
+ preservation, and the non-JSON response bypass.
344
+ **What is still missing?** Explicit re-`init()` is targeted for a later `0.3.0` pre-release.
345
+ The auth/privacy, InMemory, `Cache-Control`, ETag, `_spec_type` and non-JSON fixes are
346
+ implemented in `0.3.0a2`.
202
347
  **Is Pydantic v1 supported?** Migration compatibility only. Pydantic v1 is end-of-life
203
348
  (1.10.27 is the final release) and receives no new security fixes. Typed restoration requires
204
349
  Pydantic v2.
@@ -216,14 +361,14 @@ advisory for vulnerabilities.
216
361
  ## Known limitations in 0.3.x
217
362
 
218
363
  - No tags, stale-while-revalidate, stampede protection or POST caching.
219
- - Auth/privacy, ETag, InMemory expiry/isolation, non-JSON bypass, `_spec_type` and
220
- second-`init` fixes are not in `0.3.0a1`; they are targeted for later `0.3.0` pre-releases.
364
+ - The second-`init` fix is not in `0.3.0a2`; it is targeted for a later `0.3.0` pre-release.
365
+ The auth/privacy, InMemory, `Cache-Control`, ETag, `_spec_type` and non-JSON fixes are
366
+ implemented in `0.3.0a2`.
221
367
  - Redis standalone is verified with Redis 7 and redis-py 4.6.0; redis-py 5/6 are not
222
368
  supported by the current dependency constraint and are untested.
223
369
  - No full backend parity.
224
370
  - No perfect OpenAPI/`response_model` behavior.
225
- - No memory cap in `InMemoryBackend`; instances currently share state, and instance
226
- isolation is targeted for 0.3.0.
371
+ - No memory cap in `InMemoryBackend`.
227
372
  - Typed restoration is opt-in via `TypedJsonCoder` and requires Pydantic v2. Pydantic v1
228
373
  and unsupported annotations keep the legacy decoded behavior.
229
374
  - Python 3.8/3.9/3.10 migration compatibility is tested, but those versions are end-of-life
@@ -233,9 +378,9 @@ advisory for vulnerabilities.
233
378
 
234
379
  ## Verification checklist
235
380
 
236
- ### `0.3.0a1`
381
+ ### `0.3.0a2`
237
382
 
238
- - [ ] `pip uninstall fastapi-cache2` and `pip install fastapi-cache-stable==0.3.0a1` in a clean venv.
383
+ - [ ] `pip uninstall fastapi-cache2` and `pip install fastapi-cache-stable==0.3.0a2` in a clean venv.
239
384
  - [ ] `import fastapi_cache` and `__version__` are correct.
240
385
  - [ ] Characterization tests pass or are updated with justification.
241
386
  - [ ] HIT/MISS, status and types verified.
@@ -244,12 +389,14 @@ advisory for vulnerabilities.
244
389
 
245
390
  ### Before `0.3.0` stable
246
391
 
247
- - [ ] Two users with different credentials do not share a response.
248
- - [ ] ETag is stable across worker processes.
249
- - [ ] `Cache-Control`/`max-age` behavior is correct.
250
- - [ ] InMemory `expire=None` and instance isolation behave as documented.
251
- - [ ] Non-JSON responses (streaming/file/redirect) are bypassed.
252
- - [ ] `_spec_type` user payloads are preserved.
392
+ - [x] Two users with different credentials do not share a response (implemented in `0.3.0a2`).
393
+ - [x] ETag is stable across worker processes (implemented in `0.3.0a2`).
394
+ - [x] `Cache-Control`/`max-age` behavior is correct (implemented in `0.3.0a2`).
395
+ - [x] InMemory `expire=None` and instance isolation behave as documented (implemented in `0.3.0a2`).
396
+ - [x] Non-JSON responses and metadata-bearing `JSONResponse` are bypassed; responses with
397
+ `Set-Cookie`, `Cache-Control: no-store/private`, or a background task are never cached
398
+ (implemented in `0.3.0a2`).
399
+ - [x] `_spec_type` user payloads are preserved (implemented in `0.3.0a2`).
253
400
  - [ ] A second `init()` is explicit.
254
401
 
255
402
  ## See also