fastapi-cache-stable 0.3.0a0__tar.gz → 0.3.0a1__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/CHANGELOG.md +109 -0
  2. fastapi_cache_stable-0.3.0a1/COMPATIBILITY.md +240 -0
  3. fastapi_cache_stable-0.3.0a1/FORK_ORIGIN.md +12 -0
  4. fastapi_cache_stable-0.3.0a1/MIGRATION.md +261 -0
  5. {fastapi_cache_stable-0.3.0a0 → fastapi_cache_stable-0.3.0a1}/PKG-INFO +39 -14
  6. {fastapi_cache_stable-0.3.0a0 → fastapi_cache_stable-0.3.0a1}/README.md +38 -13
  7. fastapi_cache_stable-0.3.0a1/SECURITY.md +15 -0
  8. fastapi_cache_stable-0.3.0a1/SUPPORT.md +27 -0
  9. {fastapi_cache_stable-0.3.0a0 → fastapi_cache_stable-0.3.0a1}/fastapi_cache/__init__.py +10 -3
  10. {fastapi_cache_stable-0.3.0a0 → fastapi_cache_stable-0.3.0a1}/fastapi_cache/backends/inmemory.py +10 -7
  11. fastapi_cache_stable-0.3.0a1/fastapi_cache/backends/redis.py +80 -0
  12. {fastapi_cache_stable-0.3.0a0 → fastapi_cache_stable-0.3.0a1}/fastapi_cache/coder.py +50 -10
  13. {fastapi_cache_stable-0.3.0a0 → fastapi_cache_stable-0.3.0a1}/fastapi_cache/decorator.py +2 -0
  14. {fastapi_cache_stable-0.3.0a0 → fastapi_cache_stable-0.3.0a1}/pyproject.toml +32 -8
  15. fastapi_cache_stable-0.3.0a0/fastapi_cache/backends/redis.py +0 -30
  16. {fastapi_cache_stable-0.3.0a0 → fastapi_cache_stable-0.3.0a1}/LICENSE +0 -0
  17. {fastapi_cache_stable-0.3.0a0 → fastapi_cache_stable-0.3.0a1}/NOTICE +0 -0
  18. {fastapi_cache_stable-0.3.0a0 → fastapi_cache_stable-0.3.0a1}/fastapi_cache/backends/__init__.py +0 -0
  19. {fastapi_cache_stable-0.3.0a0 → fastapi_cache_stable-0.3.0a1}/fastapi_cache/backends/dynamodb.py +0 -0
  20. {fastapi_cache_stable-0.3.0a0 → fastapi_cache_stable-0.3.0a1}/fastapi_cache/backends/memcached.py +0 -0
  21. {fastapi_cache_stable-0.3.0a0 → fastapi_cache_stable-0.3.0a1}/fastapi_cache/key_builder.py +0 -0
  22. {fastapi_cache_stable-0.3.0a0 → fastapi_cache_stable-0.3.0a1}/fastapi_cache/py.typed +0 -0
  23. {fastapi_cache_stable-0.3.0a0 → fastapi_cache_stable-0.3.0a1}/fastapi_cache/types.py +0 -0
@@ -0,0 +1,109 @@
1
+ # ChangeLog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ This project uses [*towncrier*](https://towncrier.readthedocs.io/) and the changes for the upcoming release can be found in <https://github.com/agustin18/fastapi-cache/tree/stable/changelog.d/>.
8
+
9
+ <!-- towncrier release notes start -->
10
+
11
+ ## [0.3.0a1](https://github.com/agustin18/fastapi-cache/tree/v0.3.0a1) - 2026-11-14
12
+
13
+ ### Bugfixes
14
+
15
+ - Avoid caching explicitly returned `Response` objects with status codes >= 400. Adapted from upstream PR #575 by RitiGrover. [#2](https://github.com/agustin18/fastapi-cache/issues/2)
16
+ - Add opt-in `TypedJsonCoder` for Pydantic v2 typed restoration. `JsonCoder` keeps the legacy decoded behavior; Pydantic v1 and unsupported annotations fall back; validation errors propagate. Adapted from upstream PR #576 by bezff. [#4](https://github.com/agustin18/fastapi-cache/issues/4)
17
+ - Fix `clear(key=...)` so it deletes only the requested key, and require the `:` boundary for
18
+ namespace clears in InMemory and Redis. Redis standalone now uses `SCAN`/`UNLINK`; Redis
19
+ Cluster namespace clearing raises `NotImplementedError`. Memcached/DynamoDB clear remains
20
+ unsupported. [#7](https://github.com/agustin18/fastapi-cache/issues/7)
21
+
22
+ ### Improved Documentation
23
+
24
+ - Document and verify the legacy compatibility matrix: Python 3.8/3.9, FastAPI 0.111.1, and
25
+ Pydantic 1.10.27/2.8.2. Add a legacy CI job and a Python 3.8 wheel smoke test. No runtime
26
+ behavior changes. [#5](https://github.com/agustin18/fastapi-cache/issues/5)
27
+
28
+ ### Misc
29
+
30
+ - Bump the transitive `certifi` dev/test dependency from 2024.7.4 to 2026.10.23. [#6](https://github.com/agustin18/fastapi-cache/issues/6)
31
+ - Add a manual TestPyPI publishing workflow with a separate `testpypi` environment and Trusted Publisher. It never runs on `release: published`. [#8](https://github.com/agustin18/fastapi-cache/issues/8)
32
+ - Make PyPI publishing manual-only by removing the `release: published` trigger. [#9](https://github.com/agustin18/fastapi-cache/issues/9)
33
+
34
+ ## 0.3.0a0
35
+
36
+ - Community-maintained stable fork of fastapi-cache2, based on v0.2.2.
37
+ - Distribution renamed to `fastapi-cache-stable`; the `fastapi_cache` import and public API are unchanged.
38
+ - Declare `jinja2` as a direct dependency; the `starlette.templating` import in `coder.py` requires it.
39
+ - This is an alpha to reserve the PyPI distribution name. The 0.3.0 release will include the P0 correctness fixes and compatibility tests.
40
+
41
+ ## 0.2
42
+
43
+ ### 0.2.1
44
+ - Fix picklecoder
45
+ - Fix connection failure transparency and add logging
46
+ - Add Cache-Control and ETag on first response
47
+ - Support Async RedisCluster client from redis-py
48
+
49
+ ### 0.2.0
50
+
51
+ - Make `request` and `response` optional.
52
+ - Add typing info to the `cache` decorator.
53
+ - Support cache jinja2 template response.
54
+ - Support cache `JSONResponse`
55
+ - Add `py.typed` file and type hints
56
+ - Add TestCase
57
+ - Fix cache decorate sync function
58
+ - Transparently handle backend connection failures.
59
+
60
+ ## 0.1
61
+
62
+ ### 0.1.10
63
+
64
+ - Add `Cache-Control:no-cache` support.
65
+
66
+ ### 0.1.9
67
+
68
+ - Replace `aioredis` with `redis-py`.
69
+
70
+ ### 0.1.8
71
+
72
+ - Support `dynamodb` backend.
73
+
74
+ ### 0.1.7
75
+
76
+ - Fix default json coder for datetime.
77
+ - Add `enable` param to `init`.
78
+
79
+ ### 0.1.6
80
+
81
+ - Fix redis cache.
82
+ - Encode key builder.
83
+
84
+ ### 0.1.5
85
+
86
+ - Fix setting expire for redis (#24)
87
+ - Update expire key
88
+
89
+ ### 0.1.4
90
+
91
+ - Fix default expire for memcached. (#13)
92
+ - Update default key builder. (#12)
93
+
94
+ ### 0.1.3
95
+
96
+ - Fix cache key builder.
97
+
98
+ ### 0.1.2
99
+
100
+ - Add default config when init.
101
+ - Update JsonEncoder.
102
+
103
+ ### 0.1.1
104
+
105
+ - Add in-memory support.
106
+
107
+ ### 0.1.0
108
+
109
+ - First version release.
@@ -0,0 +1,240 @@
1
+ # Compatibility contract
2
+
3
+ `fastapi-cache-stable` is an independent, community-maintained fork of
4
+ [`fastapi-cache2`](https://pypi.org/project/fastapi-cache2/). This document defines what
5
+ "drop-in" means for this project and what we promise to keep stable.
6
+
7
+ ## What "drop-in" means
8
+
9
+ - The distribution is `fastapi-cache-stable`, but the Python import remains `fastapi_cache`.
10
+ - The public names below keep their import paths and call signatures.
11
+ - The normal success path for a GET endpoint keeps the same observable behavior: cache
12
+ miss calls the endpoint, cache hit returns the cached value, and the cache status header
13
+ reports `MISS`/`HIT`.
14
+ - Existing `@cache(...)` and `FastAPICache.init(...)` calls keep working without code changes.
15
+ - Existing custom backends, coders and key builders that implement the documented protocols
16
+ keep working.
17
+ - Migration from `fastapi-cache2` does not require application code changes for valid legacy
18
+ use cases.
19
+ - Pydantic v2 users can opt into `TypedJsonCoder` for typed restoration; the default
20
+ `JsonCoder` keeps the legacy decoded behavior. Pydantic v1 and unsupported annotations
21
+ keep the legacy behavior.
22
+ - Python 3.8/3.9 legacy compatibility is validated in CI with FastAPI 0.111.1 and
23
+ Pydantic 1.10.27/2.8.2; it is migration compatibility, not a new-production recommendation.
24
+
25
+ ## Public surface
26
+
27
+ ```python
28
+ from fastapi_cache import (
29
+ Backend,
30
+ Coder,
31
+ FastAPICache,
32
+ JsonCoder,
33
+ KeyBuilder,
34
+ TypedJsonCoder,
35
+ default_key_builder,
36
+ )
37
+ from fastapi_cache.decorator import cache
38
+ from fastapi_cache.backends.inmemory import InMemoryBackend
39
+ from fastapi_cache.backends.redis import RedisBackend
40
+ from fastapi_cache.backends.memcached import MemcachedBackend
41
+ from fastapi_cache.backends.dynamodb import DynamoBackend
42
+ ```
43
+
44
+ ### `FastAPICache`
45
+
46
+ ```python
47
+ FastAPICache.init(
48
+ backend,
49
+ prefix="",
50
+ expire=None,
51
+ coder=JsonCoder,
52
+ key_builder=default_key_builder,
53
+ cache_status_header="X-FastAPI-Cache",
54
+ enable=True,
55
+ )
56
+ FastAPICache.clear(namespace=None, key=None)
57
+ FastAPICache.reset()
58
+ FastAPICache.get_backend()
59
+ FastAPICache.get_prefix()
60
+ FastAPICache.get_expire()
61
+ FastAPICache.get_coder()
62
+ FastAPICache.get_key_builder()
63
+ FastAPICache.get_cache_status_header()
64
+ FastAPICache.get_enable()
65
+ ```
66
+
67
+ ### `@cache(...)`
68
+
69
+ ```python
70
+ cache(
71
+ expire=None,
72
+ coder=None,
73
+ key_builder=None,
74
+ namespace="",
75
+ injected_dependency_namespace="__fastapi_cache",
76
+ )
77
+ ```
78
+
79
+ ### `Backend` protocol
80
+
81
+ ```python
82
+ async def get_with_ttl(key: str) -> tuple[int, bytes | None]
83
+ async def get(key: str) -> bytes | None
84
+ async def set(key: str, value: bytes, expire: int | None = None) -> None
85
+ async def clear(namespace: str | None = None, key: str | None = None) -> int
86
+ ```
87
+
88
+ ### `KeyBuilder` protocol
89
+
90
+ ```python
91
+ def __call__(
92
+ function,
93
+ namespace: str = "",
94
+ *,
95
+ request=None,
96
+ response=None,
97
+ args: tuple,
98
+ kwargs: dict,
99
+ ) -> str | Awaitable[str]
100
+ ```
101
+
102
+ ### `Coder` protocol
103
+
104
+ ```python
105
+ classmethod encode(value) -> bytes
106
+ classmethod decode(value: bytes) -> Any
107
+ classmethod decode_as_type(value: bytes, *, type_) -> Any
108
+ ```
109
+
110
+ ## Support levels
111
+
112
+ - **Migration compatibility:** tested legacy combinations are kept so existing applications can
113
+ move to this fork without code changes. This is not a recommendation for new production
114
+ deployments.
115
+ - **Security-supported environment:** current Python, FastAPI and Pydantic releases that still
116
+ receive upstream security fixes. This project does not backport security fixes for
117
+ end-of-life upstreams.
118
+
119
+ Python 3.8, 3.9 and 3.10 are end-of-life, and Pydantic v1 is end-of-life with 1.10.27 as its
120
+ final release. They remain in the migration matrix for compatibility, not as supported
121
+ security targets.
122
+
123
+ ## Supported matrix for `0.3.x`
124
+
125
+ > The `0.3.0` line keeps `python = "^3.8"` for legacy migration. Python 3.8/3.9/3.10 and
126
+ > Pydantic v1 are end-of-life upstream; they are tested for migration, not recommended for
127
+ > new production deployments. The minimum supported Python will be revisited only after the
128
+ > compatibility matrix and an explicit floor decision.
129
+
130
+ Status definitions:
131
+
132
+ - **Verified**: tested in CI with identified versions.
133
+ - **Targeted for 0.3.0**: intended behavior, not yet guaranteed.
134
+ - **Experimental**: interface available, coverage insufficient.
135
+ - **Unsupported**: outside the compatibility contract.
136
+
137
+ | Component | Status | Notes |
138
+ |---|---|---|
139
+ | Python 3.10–3.13 | Verified | CI matrix runs the suite; Python 3.10 is EOL and kept for migration |
140
+ | Python 3.8/3.9 | Verified for migration | Legacy CI job with FastAPI 0.111.1 and Pydantic 1.10.27/2.8.2; EOL, not recommended for new production |
141
+ | Python 3.14 | Targeted | Evaluated after the first stable release |
142
+ | FastAPI | Verified with 0.111.1 and current 0.x | Older 0.100.x validation is a beta gate; no upper pin yet (`fastapi = "*"`) |
143
+ | Pydantic 2.x | Verified | Typed restoration is opt-in via `TypedJsonCoder`; default `JsonCoder` keeps legacy behavior |
144
+ | Pydantic v1 | Verified for migration | Tested with 1.10.27; EOL, no new security fixes; typed restoration is not applied |
145
+ | `Response`/`JSONResponse` annotations | Legacy decoded behavior | No Pydantic schema generation; cache hits keep working |
146
+ | 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
+ | 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 |
149
+ | Memcached | Experimental | No full `clear`/TTL parity; `clear` raises `NotImplementedError` |
150
+ | DynamoDB | Experimental | `clear` raises `NotImplementedError`; the client cleanup issue remains open and is targeted for a future fix |
151
+ | Import `fastapi_cache` | Verified | Covered by compatibility tests |
152
+
153
+ > Redis results in `0.3.0a1` cover Redis 7 with redis-py 4.6.0. Other client or server
154
+ > versions are not verified; do not infer support from the Redis 7 job alone.
155
+
156
+ ### `0.3.0a1` status
157
+
158
+ Implemented: error responses, opt-in `TypedJsonCoder`, `clear()` key/namespace semantics,
159
+ Redis Cluster namespace `NotImplementedError`, and the legacy compatibility matrix.
160
+
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.
164
+
165
+ ### Clear semantics
166
+
167
+ - `clear(key=...)` deletes exactly that key. Pass the full key as stored by the backend.
168
+ - `clear(namespace=...)` requires the `:` namespace boundary and includes nested namespaces.
169
+ - `clear()` clears the configured prefix; with an empty prefix it is a no-op.
170
+ - If both `namespace` and `key` are provided, `namespace` wins.
171
+ - Namespace clear is best-effort, not atomic. Keys added during a Redis `SCAN` may survive.
172
+ - Redis standalone uses `SCAN` + `UNLINK`; Redis Cluster namespace clear raises
173
+ `NotImplementedError`; use key-only clear or flush the database out of band.
174
+ - Memcached and DynamoDB do not implement `clear`.
175
+ - `clear()` is an administrative invalidation operation. Do not accept arbitrary keys or
176
+ namespaces from untrusted users.
177
+
178
+ ## Intentional behavior changes
179
+
180
+ 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.
184
+
185
+ | Version | Change | Why | Status |
186
+ |---|---|---|---|
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 |
198
+ | 0.3.0 | A second `FastAPICache.init(...)` is not a silent no-op | Configuration was impossible to change | Targeted |
199
+
200
+ ## Cache data compatibility
201
+
202
+ - **ETag:** the value changes once. Clients may revalidate after upgrading.
203
+ - **Key format:** if a release changes the default key format, old entries become
204
+ unreachable. Flush the cache namespace after upgrading.
205
+ - **Error responses:** old cached error entries may remain until their TTL expires. Flush
206
+ the cache namespace if you were affected.
207
+ - **Pydantic/dataclass values:** old entries encoded as plain JSON still decode; the
208
+ annotated type is restored on read. No flush required for this fix alone.
209
+
210
+ ## How compatibility is tested
211
+
212
+ - API signature tests for the public names above.
213
+ - Characterization tests for the normal GET success path.
214
+ - Regression tests for every behavior change.
215
+ - CI tests Python 3.10–3.13 with resolver-selected FastAPI and Pydantic versions.
216
+ - A `legacy-compat` job tests Python 3.8/3.9 with FastAPI 0.111.1 and Pydantic 1.10.27/2.8.2,
217
+ plus Python 3.10/3.11 with Pydantic 1.10.27.
218
+ - A `legacy-smoke` job builds the wheel and installs it on Python 3.8 with Pydantic 1.10.27.
219
+ - Wheel and sdist smoke tests in a clean virtual environment.
220
+ - Redis 7 integration tests run in CI; Memcached and DynamoDB backend integration tests are
221
+ planned.
222
+ - Migration tests that install the package and run a small app.
223
+
224
+ ## If we break something
225
+
226
+ We treat a compatibility break as a bug:
227
+
228
+ 1. Open an issue (when issues are enabled) or a private security advisory for a
229
+ vulnerability.
230
+ 2. Document the break and the rollback path in `MIGRATION.md`.
231
+ 3. Publish a patch release with a regression test.
232
+ 4. If the break is unavoidable, announce it before the release and provide a migration path.
233
+
234
+ ## Not covered by this contract
235
+
236
+ - Private APIs of FastAPI, Starlette or Pydantic.
237
+ - Behavior of optional backends marked experimental.
238
+ - Undocumented attributes such as `FastAPICache._backend` or `_enable`.
239
+ - Exact cache key strings, ETag values, header ordering or log messages.
240
+ - Performance characteristics.
@@ -0,0 +1,12 @@
1
+ # Fork origin
2
+
3
+ This project is a community-maintained fork of fastapi-cache (PyPI: `fastapi-cache2`),
4
+ originally by long2ice and contributors:
5
+
6
+ https://github.com/long2ice/fastapi-cache
7
+
8
+ - Baseline: `v0.2.2` (2024-07-24).
9
+ - License: Apache-2.0 (see `LICENSE`).
10
+ - This fork is not affiliated with or endorsed by the original author.
11
+ - The `fastapi_cache` import and public API are preserved for drop-in compatibility.
12
+ - Changes are documented in `CHANGELOG.md`.
@@ -0,0 +1,261 @@
1
+ # Migrating from fastapi-cache2
2
+
3
+ `fastapi-cache-stable` is an independent, community-maintained fork of
4
+ [`fastapi-cache2`](https://pypi.org/project/fastapi-cache2/). The Python import is unchanged:
5
+
6
+ ```python
7
+ from fastapi_cache import FastAPICache
8
+ from fastapi_cache.backends.redis import RedisBackend
9
+ from fastapi_cache.decorator import cache
10
+ ```
11
+
12
+ The goal is a drop-in replacement for the common case: same import, same public API, same
13
+ normal success-path behavior. Bug fixes that change edge-case behavior are listed below and
14
+ are covered by regression tests. See [`COMPATIBILITY.md`](COMPATIBILITY.md) for the full
15
+ contract.
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.
22
+
23
+ ## Who should migrate
24
+
25
+ - You use `fastapi-cache2` 0.2.2 on Python 3.8–3.13.
26
+ - You use `InMemoryBackend` or `RedisBackend` (standalone Redis).
27
+ - Your endpoints are GET and return JSON, Pydantic models, dataclasses or standard types.
28
+ - You need a maintained package without changing the `fastapi_cache` import.
29
+
30
+ Python 3.8/3.9/3.10 and Pydantic v1 are end-of-life upstream. They remain supported for
31
+ migration so existing applications can move without code changes; they are not a security
32
+ recommendation for new deployments.
33
+
34
+ The default `JsonCoder` keeps the legacy decoded behavior. Pydantic v2 users can opt into
35
+ typed restoration with `TypedJsonCoder`; Pydantic v1 users keep the legacy behavior, so
36
+ migration does not require a Pydantic upgrade or application changes.
37
+
38
+ ```python
39
+ from fastapi_cache import FastAPICache
40
+ from fastapi_cache.coder import TypedJsonCoder
41
+
42
+ FastAPICache.init(backend, coder=TypedJsonCoder)
43
+ ```
44
+
45
+ You can also enable it per endpoint with `@cache(coder=TypedJsonCoder)`.
46
+
47
+ `TypedJsonCoder` validates cached data and propagates validation errors. It only falls back
48
+ for Pydantic v1 models and annotations that cannot be represented by a Pydantic v2 schema.
49
+
50
+ ## Who should not migrate yet
51
+
52
+ - 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 use Redis Cluster and need complete namespace clearing.
56
+ - You need typed restoration on Pydantic v1; the legacy decoded behavior is preserved instead.
57
+ Pydantic v1 is end-of-life; plan an upgrade to Pydantic v2 for typed restoration and
58
+ security fixes.
59
+ - You need tags, stale-while-revalidate, stampede protection or POST caching.
60
+ - You need perfect OpenAPI/`response_model` behavior or `fastapi-pagination`.
61
+
62
+ ## Install
63
+
64
+ ```sh
65
+ pip uninstall -y fastapi-cache2
66
+ pip install fastapi-cache-stable
67
+ # with extras:
68
+ pip install "fastapi-cache-stable[redis]"
69
+ ```
70
+
71
+ Do **not** install both distributions in the same environment: they provide the same
72
+ `fastapi_cache` package and the version metadata becomes ambiguous.
73
+
74
+ Verify:
75
+
76
+ ```sh
77
+ python -c "import fastapi_cache; print(fastapi_cache.__version__)"
78
+ python -c "from fastapi_cache import FastAPICache; print('ok')"
79
+ ```
80
+
81
+ ### Alpha installation from TestPyPI
82
+
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
+
87
+ ```sh
88
+ python -m pip download --no-deps --only-binary=:all: \
89
+ --index-url https://test.pypi.org/simple/ \
90
+ -d testpypi-dist \
91
+ "fastapi-cache-stable==0.3.0a1"
92
+
93
+ python -m pip install testpypi-dist/*.whl
94
+ python -m pip check
95
+ python -c "import fastapi_cache; print(fastapi_cache.__version__)"
96
+ ```
97
+
98
+ 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.
101
+
102
+ ## Compatibility matrix
103
+
104
+ - **Verified**: tested in CI with identified versions.
105
+ - **Targeted for 0.3.0**: intended behavior, not yet guaranteed.
106
+ - **Experimental**: interface available, coverage insufficient.
107
+ - **Unsupported**: outside the compatibility contract.
108
+
109
+ | Component | Status | Notes |
110
+ |---|---|---|
111
+ | Python 3.10–3.13 | Verified | CI matrix runs the suite; Python 3.10 is EOL and kept for migration |
112
+ | Python 3.8/3.9 | Verified for migration | Legacy CI job with FastAPI 0.111.1 and Pydantic 1.10.27/2.8.2; EOL, not recommended for new production |
113
+ | Python 3.14 | Targeted | Evaluated after the first stable release |
114
+ | FastAPI | Verified with 0.111.1 and current 0.x | Older 0.100.x validation is a beta gate; no upper pin yet (`fastapi = "*"`) |
115
+ | Pydantic 2.x | Verified | Typed restoration is opt-in via `TypedJsonCoder`; default `JsonCoder` keeps legacy behavior |
116
+ | Pydantic v1 | Verified for migration | Tested with 1.10.27; EOL, no new security fixes; typed restoration is not applied |
117
+ | `Response`/`JSONResponse` annotations | Legacy decoded behavior | No Pydantic schema generation; cache hits keep working |
118
+ | 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
+ | 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 |
121
+ | Memcached | Experimental | No full `clear`/TTL parity |
122
+ | DynamoDB | Experimental | `clear` is not implemented; the client cleanup issue remains open and is targeted for a future fix |
123
+ | Import `fastapi_cache` | Verified | Covered by compatibility tests |
124
+
125
+ > The Redis integration job installs the resolver-selected `redis` version from the project
126
+ > 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`.
128
+
129
+ ## Behavior changes in 0.3.0
130
+
131
+ 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
+
136
+ | Change | Before (0.2.2) | After (0.3.0) | Status |
137
+ |---|---|---|---|
138
+ | Error responses | A cached 404 could be returned as 200 | Responses with status >= 400 are not cached | Implemented in 0.3.0a1 |
139
+ | 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 |
142
+ | `clear(key=...)` | Deleted the whole prefix namespace | Deletes only that key; pass the full key | Implemented in 0.3.0a1 |
143
+ | Namespace boundary | `clear("app:user")` also deleted `app:users` | Requires the `:` boundary | Implemented in 0.3.0a1 |
144
+ | 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
+ | Second `init` | Silent no-op | Reconfiguration is explicit and documented | Targeted |
150
+
151
+ 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.
153
+
154
+ **Action required:** if you were affected by cached error responses or by `clear(key=...)`,
155
+ flush the cache namespace after upgrading. If you relied on `clear(key=...)` clearing the whole
156
+ prefix, switch to `clear()` or `clear(namespace=...)`. If you relied on `clear("app:user")`
157
+ deleting `app:users`, use the exact namespace. Redis Cluster users must use key-only clear or
158
+ flush the database out of band. Namespace clear is best-effort and not atomic. `clear()` is an
159
+ administrative operation; do not expose it to untrusted input. If the ETag changes, clients may
160
+ revalidate once.
161
+
162
+ ## Step by step
163
+
164
+ 1. **Inventory.** Note your `fastapi-cache2` version, backend, return types, `clear` usage,
165
+ `key_builder`, headers and authentication.
166
+ 2. **Characterization tests.** Before migrating, add tests for HIT/MISS, status codes,
167
+ headers and return types so you can compare.
168
+ 3. **Clean environment.** Create a virtualenv, uninstall `fastapi-cache2`, install
169
+ `fastapi-cache-stable`, and verify `fastapi_cache.__version__`.
170
+ 4. **Configure once.** Call `FastAPICache.init(...)` once during startup. Define prefix,
171
+ 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.
176
+ 7. **Observe.** Compare HIT/MISS, latency, errors and memory with your baseline.
177
+ 8. **Roll back if needed.** See below.
178
+
179
+ ## Rollback
180
+
181
+ ```sh
182
+ pip uninstall -y fastapi-cache-stable
183
+ pip install "fastapi-cache2==0.2.2"
184
+ # clear the cache namespace if the key format changed
185
+ ```
186
+
187
+ Keep the previous version pinned and a backup of your configuration. Rollback does not
188
+ restore cache entries written with the new format; they are regenerated.
189
+
190
+ ## FAQ
191
+
192
+ **Does the import change?** No: `fastapi_cache`.
193
+ **Can I install both packages?** No, not in the same environment.
194
+ **What happens to my cached data?** If the key format or ETag changed, entries are
195
+ 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.
202
+ **Is Pydantic v1 supported?** Migration compatibility only. Pydantic v1 is end-of-life
203
+ (1.10.27 is the final release) and receives no new security fixes. Typed restoration requires
204
+ Pydantic v2.
205
+ **Is Python 3.8/3.9 supported?** Migration compatibility is tested. Python 3.8/3.9/3.10 are
206
+ end-of-life and are not recommended for new production deployments.
207
+ **Is Redis Cluster supported?** Only with the documented limitations; complete namespace
208
+ clearing is not promised.
209
+ **Are Memcached and DynamoDB supported?** Experimental until they have parity tests.
210
+ DynamoDB `clear` is not implemented and the client cleanup issue remains open.
211
+ **Is this an official successor?** No. It is an independent fork, not endorsed by the
212
+ original author.
213
+ **How do I report a bug?** Use the fork's issues (when enabled) or a private security
214
+ advisory for vulnerabilities.
215
+
216
+ ## Known limitations in 0.3.x
217
+
218
+ - 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.
221
+ - Redis standalone is verified with Redis 7 and redis-py 4.6.0; redis-py 5/6 are not
222
+ supported by the current dependency constraint and are untested.
223
+ - No full backend parity.
224
+ - 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.
227
+ - Typed restoration is opt-in via `TypedJsonCoder` and requires Pydantic v2. Pydantic v1
228
+ and unsupported annotations keep the legacy decoded behavior.
229
+ - Python 3.8/3.9/3.10 migration compatibility is tested, but those versions are end-of-life
230
+ and are not recommended for new production deployments.
231
+ - The 24-month `1.x` support window in `SUPPORT.md` is conditional on the `1.x` release and
232
+ a co-maintainer being in place; no multi-year promise is active today.
233
+
234
+ ## Verification checklist
235
+
236
+ ### `0.3.0a1`
237
+
238
+ - [ ] `pip uninstall fastapi-cache2` and `pip install fastapi-cache-stable==0.3.0a1` in a clean venv.
239
+ - [ ] `import fastapi_cache` and `__version__` are correct.
240
+ - [ ] Characterization tests pass or are updated with justification.
241
+ - [ ] HIT/MISS, status and types verified.
242
+ - [ ] `clear(namespace)` and `clear(key)` verified.
243
+ - [ ] Rollback tested in staging.
244
+
245
+ ### Before `0.3.0` stable
246
+
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.
253
+ - [ ] A second `init()` is explicit.
254
+
255
+ ## See also
256
+
257
+ - [`COMPATIBILITY.md`](COMPATIBILITY.md) — compatibility contract.
258
+ - [`CHANGELOG.md`](CHANGELOG.md) — release notes.
259
+ - [`SUPPORT.md`](SUPPORT.md) — support policy.
260
+ - [`SECURITY.md`](SECURITY.md) — security policy.
261
+ - [`FORK_ORIGIN.md`](FORK_ORIGIN.md) — fork origin and attribution.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fastapi-cache-stable
3
- Version: 0.3.0a0
3
+ Version: 0.3.0a1
4
4
  Summary: Community-maintained, drop-in stable fork of fastapi-cache2
5
5
  License: Apache-2.0
6
6
  License-File: LICENSE
@@ -43,12 +43,22 @@ Description-Content-Type: text/markdown
43
43
  # fastapi-cache-stable
44
44
 
45
45
  > **Community-maintained stable fork of fastapi-cache2.**
46
- > This is an alpha (`0.3.0a0`) based on `v0.2.2`. The `fastapi_cache` import and public API are unchanged.
47
- > See [MIGRATION.md](MIGRATION.md) and [SUPPORT.md](SUPPORT.md). Not affiliated with the original author.
46
+ > This is an alpha (`0.3.0a1`) based on `v0.2.2`. It is experimental and not recommended for
47
+ > production. The `fastapi_cache` import and public API are unchanged.
48
+ > See [COMPATIBILITY.md](COMPATIBILITY.md), [MIGRATION.md](MIGRATION.md), [SUPPORT.md](SUPPORT.md),
49
+ > [SECURITY.md](SECURITY.md) and [FORK_ORIGIN.md](FORK_ORIGIN.md). Not affiliated with the original author.
50
+
51
+ > **Implemented in this alpha:** error responses are not cached, opt-in `TypedJsonCoder` for
52
+ > Pydantic v2, and the `clear()` fixes. Auth/privacy, ETag, InMemory expiry/isolation, non-JSON
53
+ > bypass and `_spec_type` fixes are targeted for later `0.3.0` pre-releases; see
54
+ > [MIGRATION.md](MIGRATION.md).
55
+
56
+ > **Branch model:** `stable` is the only maintained and release branch. `main` mirrors the
57
+ > upstream project and is not a second development branch.
48
58
 
49
59
  [![pypi](https://img.shields.io/pypi/v/fastapi-cache-stable.svg?style=flat)](https://pypi.org/p/fastapi-cache-stable)
50
60
  [![license](https://img.shields.io/github/license/agustin18/fastapi-cache)](https://github.com/agustin18/fastapi-cache/blob/stable/LICENSE)
51
- [![CI/CD](https://github.com/agustin18/fastapi-cache/actions/workflows/ci-cd.yml/badge.svg)](https://github.com/agustin18/fastapi-cache/actions/workflows/ci-cd.yml)
61
+ [![CI](https://github.com/agustin18/fastapi-cache/actions/workflows/ci.yml/badge.svg)](https://github.com/agustin18/fastapi-cache/actions/workflows/ci.yml)
52
62
 
53
63
  ## Introduction
54
64
 
@@ -59,7 +69,11 @@ backends supporting Redis, Memcached, and Amazon DynamoDB.
59
69
 
60
70
  - Supports `redis`, `memcache`, `dynamodb`, and `in-memory` backends.
61
71
  - Easy integration with [FastAPI](https://fastapi.tiangolo.com/).
62
- - Support for HTTP cache headers like `ETag` and `Cache-Control`, as well as conditional `If-Match-None` requests.
72
+ - Inherited `ETag` and `Cache-Control` support, including conditional `If-None-Match`
73
+ requests. Correctness fixes for these headers are targeted for later `0.3.0` pre-releases.
74
+
75
+ > **Alpha caveat:** `ETag`/`Cache-Control` correctness, auth/privacy defaults and InMemory
76
+ > expiration/isolation are not fixed in `0.3.0a1`. See [COMPATIBILITY.md](COMPATIBILITY.md).
63
77
 
64
78
  ## Requirements
65
79
 
@@ -168,25 +182,36 @@ prefix used if those names would clash anyway.
168
182
 
169
183
  ### Supported data types
170
184
 
171
- When using the (default) `JsonCoder`, the cache can store any data type that FastAPI can convert to JSON, including Pydantic models and dataclasses,
172
- _provided_ that your endpoint has a correct return type annotation. An
173
- annotation is not needed if the return type is a standard JSON-supported Python
174
- type such as a dictionary or a list.
185
+ The default `JsonCoder` stores any data type that FastAPI can convert to JSON, including
186
+ Pydantic models and dataclasses. On a cache hit it returns the decoded JSON value (plain
187
+ dicts/lists), not the annotated model; this is the legacy `fastapi-cache2` behavior.
188
+
189
+ Pydantic v2 users can opt into typed restoration with `TypedJsonCoder`:
190
+
191
+ ```python
192
+ from fastapi_cache import FastAPICache
193
+ from fastapi_cache.coder import TypedJsonCoder
175
194
 
176
- E.g. for an endpoint that returns a Pydantic model named `SomeModel`, the return annotation is used to ensure that the cached result is converted back to the correct class:
195
+ FastAPICache.init(backend, coder=TypedJsonCoder)
196
+ ```
197
+
198
+ or per endpoint:
177
199
 
178
200
  ```python
179
201
  from .models import SomeModel, create_some_model
180
202
 
181
203
  @app.get("/foo")
182
- @cache(expire=60)
204
+ @cache(expire=60, coder=TypedJsonCoder)
183
205
  async def foo() -> SomeModel:
184
206
  return create_some_model()
185
207
  ```
186
208
 
187
- It is not sufficient to configure a response model in the route decorator; the cache needs to know what the method itself returns. If no return type decorator is given, the primitive JSON type is returned instead.
209
+ `TypedJsonCoder` uses the endpoint return annotation to restore the annotated type and
210
+ propagates validation errors. It requires Pydantic v2; Pydantic v1 and annotations that
211
+ cannot be represented by a Pydantic v2 schema keep the legacy decoded behavior.
188
212
 
189
- For broader type support, use the `fastapi_cache.coder.PickleCoder` or implement a custom coder (see below).
213
+ For broader type support, use `fastapi_cache.coder.PickleCoder` or implement a custom coder
214
+ (see below).
190
215
 
191
216
  ### Custom coder
192
217
 
@@ -277,5 +302,5 @@ xdg-open htmlcov/index.html
277
302
 
278
303
  ## License
279
304
 
280
- This project is licensed under the [Apache-2.0](https://github.com/long2ice/fastapi-cache/blob/master/LICENSE) License.
305
+ This project is licensed under the [Apache-2.0](https://github.com/agustin18/fastapi-cache/blob/stable/LICENSE) License.
281
306
 
@@ -1,12 +1,22 @@
1
1
  # fastapi-cache-stable
2
2
 
3
3
  > **Community-maintained stable fork of fastapi-cache2.**
4
- > This is an alpha (`0.3.0a0`) based on `v0.2.2`. The `fastapi_cache` import and public API are unchanged.
5
- > See [MIGRATION.md](MIGRATION.md) and [SUPPORT.md](SUPPORT.md). Not affiliated with the original author.
4
+ > This is an alpha (`0.3.0a1`) based on `v0.2.2`. It is experimental and not recommended for
5
+ > production. The `fastapi_cache` import and public API are unchanged.
6
+ > See [COMPATIBILITY.md](COMPATIBILITY.md), [MIGRATION.md](MIGRATION.md), [SUPPORT.md](SUPPORT.md),
7
+ > [SECURITY.md](SECURITY.md) and [FORK_ORIGIN.md](FORK_ORIGIN.md). Not affiliated with the original author.
8
+
9
+ > **Implemented in this alpha:** error responses are not cached, opt-in `TypedJsonCoder` for
10
+ > Pydantic v2, and the `clear()` fixes. Auth/privacy, ETag, InMemory expiry/isolation, non-JSON
11
+ > bypass and `_spec_type` fixes are targeted for later `0.3.0` pre-releases; see
12
+ > [MIGRATION.md](MIGRATION.md).
13
+
14
+ > **Branch model:** `stable` is the only maintained and release branch. `main` mirrors the
15
+ > upstream project and is not a second development branch.
6
16
 
7
17
  [![pypi](https://img.shields.io/pypi/v/fastapi-cache-stable.svg?style=flat)](https://pypi.org/p/fastapi-cache-stable)
8
18
  [![license](https://img.shields.io/github/license/agustin18/fastapi-cache)](https://github.com/agustin18/fastapi-cache/blob/stable/LICENSE)
9
- [![CI/CD](https://github.com/agustin18/fastapi-cache/actions/workflows/ci-cd.yml/badge.svg)](https://github.com/agustin18/fastapi-cache/actions/workflows/ci-cd.yml)
19
+ [![CI](https://github.com/agustin18/fastapi-cache/actions/workflows/ci.yml/badge.svg)](https://github.com/agustin18/fastapi-cache/actions/workflows/ci.yml)
10
20
 
11
21
  ## Introduction
12
22
 
@@ -17,7 +27,11 @@ backends supporting Redis, Memcached, and Amazon DynamoDB.
17
27
 
18
28
  - Supports `redis`, `memcache`, `dynamodb`, and `in-memory` backends.
19
29
  - Easy integration with [FastAPI](https://fastapi.tiangolo.com/).
20
- - Support for HTTP cache headers like `ETag` and `Cache-Control`, as well as conditional `If-Match-None` requests.
30
+ - Inherited `ETag` and `Cache-Control` support, including conditional `If-None-Match`
31
+ requests. Correctness fixes for these headers are targeted for later `0.3.0` pre-releases.
32
+
33
+ > **Alpha caveat:** `ETag`/`Cache-Control` correctness, auth/privacy defaults and InMemory
34
+ > expiration/isolation are not fixed in `0.3.0a1`. See [COMPATIBILITY.md](COMPATIBILITY.md).
21
35
 
22
36
  ## Requirements
23
37
 
@@ -126,25 +140,36 @@ prefix used if those names would clash anyway.
126
140
 
127
141
  ### Supported data types
128
142
 
129
- When using the (default) `JsonCoder`, the cache can store any data type that FastAPI can convert to JSON, including Pydantic models and dataclasses,
130
- _provided_ that your endpoint has a correct return type annotation. An
131
- annotation is not needed if the return type is a standard JSON-supported Python
132
- type such as a dictionary or a list.
143
+ The default `JsonCoder` stores any data type that FastAPI can convert to JSON, including
144
+ Pydantic models and dataclasses. On a cache hit it returns the decoded JSON value (plain
145
+ dicts/lists), not the annotated model; this is the legacy `fastapi-cache2` behavior.
146
+
147
+ Pydantic v2 users can opt into typed restoration with `TypedJsonCoder`:
148
+
149
+ ```python
150
+ from fastapi_cache import FastAPICache
151
+ from fastapi_cache.coder import TypedJsonCoder
133
152
 
134
- E.g. for an endpoint that returns a Pydantic model named `SomeModel`, the return annotation is used to ensure that the cached result is converted back to the correct class:
153
+ FastAPICache.init(backend, coder=TypedJsonCoder)
154
+ ```
155
+
156
+ or per endpoint:
135
157
 
136
158
  ```python
137
159
  from .models import SomeModel, create_some_model
138
160
 
139
161
  @app.get("/foo")
140
- @cache(expire=60)
162
+ @cache(expire=60, coder=TypedJsonCoder)
141
163
  async def foo() -> SomeModel:
142
164
  return create_some_model()
143
165
  ```
144
166
 
145
- It is not sufficient to configure a response model in the route decorator; the cache needs to know what the method itself returns. If no return type decorator is given, the primitive JSON type is returned instead.
167
+ `TypedJsonCoder` uses the endpoint return annotation to restore the annotated type and
168
+ propagates validation errors. It requires Pydantic v2; Pydantic v1 and annotations that
169
+ cannot be represented by a Pydantic v2 schema keep the legacy decoded behavior.
146
170
 
147
- For broader type support, use the `fastapi_cache.coder.PickleCoder` or implement a custom coder (see below).
171
+ For broader type support, use `fastapi_cache.coder.PickleCoder` or implement a custom coder
172
+ (see below).
148
173
 
149
174
  ### Custom coder
150
175
 
@@ -235,4 +260,4 @@ xdg-open htmlcov/index.html
235
260
 
236
261
  ## License
237
262
 
238
- This project is licensed under the [Apache-2.0](https://github.com/long2ice/fastapi-cache/blob/master/LICENSE) License.
263
+ This project is licensed under the [Apache-2.0](https://github.com/agustin18/fastapi-cache/blob/stable/LICENSE) License.
@@ -0,0 +1,15 @@
1
+ # Security policy
2
+
3
+ ## Supported versions
4
+
5
+ - `0.3.x`: security fixes.
6
+ - `1.x`: security fixes (planned).
7
+
8
+ ## Reporting a vulnerability
9
+
10
+ Use GitHub private vulnerability reporting:
11
+
12
+ https://github.com/agustin18/fastapi-cache/security/advisories/new
13
+
14
+ Do not open a public issue for security reports. We aim to acknowledge within
15
+ 3 business days and provide a remediation plan within 10 business days.
@@ -0,0 +1,27 @@
1
+ # Support policy
2
+
3
+ `fastapi-cache-stable` is a community-maintained, drop-in stable fork of
4
+ fastapi-cache2.
5
+
6
+ ## Supported lines
7
+
8
+ - `0.3.x`: security and critical correctness fixes for 12 months after the first stable
9
+ `0.3.0` release, on a best-effort basis and subject to maintainer capacity. The window is
10
+ a target, not a guarantee.
11
+ - `1.x` (planned): if and when `1.0.0` is released with a co-maintainer in place, security
12
+ and critical correctness fixes for 24 months after that release. This is a conditional
13
+ plan, not an active commitment.
14
+ - Feature work is best effort.
15
+ - The support window is reviewed annually and may be revised with a public notice.
16
+
17
+ ## Handover
18
+
19
+ - A co-maintainer is required before `1.0.0`. If none is available, `1.0.0` will not be
20
+ released and the 24-month window does not start.
21
+ - If the maintainer cannot continue, the project will be handed to a co-maintainer or moved
22
+ to maintenance mode with a public notice.
23
+ - The code is Apache-2.0 and can be forked.
24
+
25
+ ## Security
26
+
27
+ See `SECURITY.md`.
@@ -1,7 +1,7 @@
1
1
  from importlib.metadata import version
2
2
  from typing import ClassVar, Optional, Type
3
3
 
4
- from fastapi_cache.coder import Coder, JsonCoder
4
+ from fastapi_cache.coder import Coder, JsonCoder, TypedJsonCoder
5
5
  from fastapi_cache.key_builder import default_key_builder
6
6
  from fastapi_cache.types import Backend, KeyBuilder
7
7
 
@@ -12,6 +12,7 @@ __all__ = [
12
12
  "FastAPICache",
13
13
  "JsonCoder",
14
14
  "KeyBuilder",
15
+ "TypedJsonCoder",
15
16
  "default_key_builder",
16
17
  ]
17
18
 
@@ -99,5 +100,11 @@ class FastAPICache:
99
100
  assert ( # noqa: S101
100
101
  cls._backend and cls._prefix is not None
101
102
  ), "You must call init first!"
102
- namespace = cls._prefix + (":" + namespace if namespace else "")
103
- return await cls._backend.clear(namespace, key)
103
+ if namespace is not None or key is None:
104
+ effective_namespace = cls._prefix + (
105
+ ":" + namespace if namespace else ""
106
+ )
107
+ if not effective_namespace:
108
+ return 0
109
+ return await cls._backend.clear(namespace=effective_namespace)
110
+ return await cls._backend.clear(key=key)
@@ -49,13 +49,16 @@ class InMemoryBackend(Backend):
49
49
 
50
50
  async def clear(self, namespace: Optional[str] = None, key: Optional[str] = None) -> int:
51
51
  count = 0
52
- if namespace:
53
- keys = list(self._store.keys())
54
- for key in keys:
55
- if key.startswith(namespace):
52
+ async with self._lock:
53
+ if namespace:
54
+ boundary = namespace + ":"
55
+ keys = list(self._store.keys())
56
+ for cache_key in keys:
57
+ if cache_key.startswith(boundary):
58
+ del self._store[cache_key]
59
+ count += 1
60
+ elif key:
61
+ if key in self._store:
56
62
  del self._store[key]
57
63
  count += 1
58
- elif key:
59
- del self._store[key]
60
- count += 1
61
64
  return count
@@ -0,0 +1,80 @@
1
+ from typing import List, Optional, Tuple, Union
2
+
3
+ from redis.asyncio.client import Redis
4
+ from redis.asyncio.cluster import RedisCluster
5
+
6
+ from fastapi_cache.types import Backend
7
+
8
+ _GLOB_METACHARACTERS = frozenset("*?[]\\")
9
+
10
+
11
+ def _escape_glob(value: str) -> str:
12
+ return "".join(
13
+ "\\" + character if character in _GLOB_METACHARACTERS else character
14
+ for character in value
15
+ )
16
+
17
+
18
+ def _matches_namespace(
19
+ cache_key: Union[bytes, str], boundary: str, boundary_bytes: bytes
20
+ ) -> bool:
21
+ if isinstance(cache_key, bytes):
22
+ return cache_key.startswith(boundary_bytes)
23
+ return cache_key.startswith(boundary)
24
+
25
+
26
+ class RedisBackend(Backend):
27
+ _SCAN_COUNT = 1000
28
+ _UNLINK_BATCH_SIZE = 500
29
+
30
+ def __init__(self, redis: Union["Redis[bytes]", "RedisCluster[bytes]"]):
31
+ self.redis = redis
32
+ self.is_cluster: bool = isinstance(redis, RedisCluster)
33
+
34
+ async def get_with_ttl(self, key: str) -> Tuple[int, Optional[bytes]]:
35
+ async with self.redis.pipeline(transaction=not self.is_cluster) as pipe:
36
+ return await pipe.ttl(key).get(key).execute() # type: ignore[union-attr,no-any-return]
37
+
38
+ async def get(self, key: str) -> Optional[bytes]:
39
+ return await self.redis.get(key) # type: ignore[union-attr]
40
+
41
+ async def set(self, key: str, value: bytes, expire: Optional[int] = None) -> None:
42
+ await self.redis.set(key, value, ex=expire) # type: ignore[union-attr]
43
+
44
+ async def clear(self, namespace: Optional[str] = None, key: Optional[str] = None) -> int:
45
+ if namespace:
46
+ if self.is_cluster:
47
+ raise NotImplementedError(
48
+ "Redis Cluster namespace clearing is not supported; "
49
+ "use clear(key=...) or flush the database out of band"
50
+ )
51
+ return await self._clear_namespace(namespace)
52
+ if key:
53
+ return await self._unlink([key])
54
+ return 0
55
+
56
+ async def _clear_namespace(self, namespace: str) -> int:
57
+ encoder = self.redis.get_encoder() # type: ignore[union-attr]
58
+ boundary = namespace + ":"
59
+ boundary_bytes = bytes(encoder.encode(boundary))
60
+ pattern = f"{_escape_glob(namespace)}:*"
61
+ count = 0
62
+ batch: List[Union[bytes, str]] = []
63
+ async for cache_key in self.redis.scan_iter( # type: ignore[union-attr]
64
+ match=pattern, count=self._SCAN_COUNT
65
+ ):
66
+ if not _matches_namespace(cache_key, boundary, boundary_bytes):
67
+ continue
68
+ batch.append(cache_key)
69
+ if len(batch) >= self._UNLINK_BATCH_SIZE:
70
+ count += await self._unlink(batch)
71
+ batch.clear()
72
+ if batch:
73
+ count += await self._unlink(batch)
74
+ return count
75
+
76
+ async def _unlink(self, keys: List[Union[bytes, str]]) -> int:
77
+ unlink = getattr(self.redis, "unlink", None)
78
+ if unlink is None:
79
+ return await self.redis.delete(*keys) # type: ignore[union-attr]
80
+ return await unlink(*keys) # type: ignore[no-any-return]
@@ -10,19 +10,29 @@ from typing import (
10
10
  Optional,
11
11
  TypeVar,
12
12
  Union,
13
+ get_args,
13
14
  overload,
14
15
  )
15
16
 
16
17
  import pendulum
18
+ import pydantic
17
19
  from fastapi.encoders import jsonable_encoder
18
20
  from starlette.responses import JSONResponse
19
21
  from starlette.templating import (
20
22
  _TemplateResponse as TemplateResponse, # pyright: ignore[reportPrivateUsage]
21
23
  )
22
24
 
25
+ TypeAdapter = getattr(pydantic, "TypeAdapter", None)
23
26
 
24
- class ModelField:
25
- pass
27
+ _TYPE_ADAPTER_ERRORS = tuple(
28
+ error
29
+ for error in (
30
+ getattr(pydantic, "PydanticSchemaGenerationError", None),
31
+ getattr(pydantic, "PydanticUserError", None),
32
+ TypeError,
33
+ )
34
+ if error is not None
35
+ )
26
36
 
27
37
  _T = TypeVar("_T", bound=type)
28
38
 
@@ -35,6 +45,18 @@ CONVERTERS: Dict[str, Callable[[str], Any]] = {
35
45
  }
36
46
 
37
47
 
48
+ def _is_pydantic_v1_model(type_: Any) -> bool:
49
+ v1 = getattr(pydantic, "v1", None)
50
+ base: Any = getattr(v1, "BaseModel", None)
51
+ return bool(base) and isinstance(type_, type) and issubclass(type_, base)
52
+
53
+
54
+ def _contains_pydantic_v1_model(type_: Any) -> bool:
55
+ if _is_pydantic_v1_model(type_):
56
+ return True
57
+ return any(_contains_pydantic_v1_model(arg) for arg in get_args(type_))
58
+
59
+
38
60
  class JsonEncoder(json.JSONEncoder):
39
61
  def default(self, o: Any) -> Any:
40
62
  if isinstance(o, datetime.datetime):
@@ -67,13 +89,6 @@ class Coder:
67
89
  def decode(cls, value: bytes) -> Any:
68
90
  raise NotImplementedError
69
91
 
70
- # (Shared) cache for endpoint return types to Pydantic model fields.
71
- # Note that subclasses share this cache! If a subclass overrides the
72
- # decode_as_type method and then stores a different kind of field for a
73
- # given type, do make sure that the subclass provides its own class
74
- # attribute for this cache.
75
- _type_field_cache: ClassVar[Dict[Any, ModelField]] = {}
76
-
77
92
  @overload
78
93
  @classmethod
79
94
  def decode_as_type(cls, value: bytes, *, type_: _T) -> _T:
@@ -99,7 +114,7 @@ class JsonCoder(Coder):
99
114
  @classmethod
100
115
  def encode(cls, value: Any) -> bytes:
101
116
  if isinstance(value, JSONResponse):
102
- return value.body
117
+ return bytes(value.body)
103
118
  return json.dumps(value, cls=JsonEncoder).encode()
104
119
 
105
120
  @classmethod
@@ -110,6 +125,31 @@ class JsonCoder(Coder):
110
125
  return json.loads(value.decode(), object_hook=object_hook)
111
126
 
112
127
 
128
+ class TypedJsonCoder(JsonCoder):
129
+ _type_adapter_cache: ClassVar[Dict[Any, Any]] = {}
130
+
131
+ @classmethod
132
+ def decode_as_type(cls, value: bytes, *, type_: Any) -> Any:
133
+ result = cls.decode(value)
134
+ if type_ is None or _contains_pydantic_v1_model(type_):
135
+ return result
136
+
137
+ type_adapter = TypeAdapter
138
+ if type_adapter is None:
139
+ return result
140
+
141
+ adapter: Any
142
+ try:
143
+ adapter = cls._type_adapter_cache[type_]
144
+ except KeyError:
145
+ try:
146
+ adapter = type_adapter(type_)
147
+ except _TYPE_ADAPTER_ERRORS:
148
+ return result
149
+ cls._type_adapter_cache[type_] = adapter
150
+ return adapter.validate_python(result)
151
+
152
+
113
153
  class PickleCoder(Coder):
114
154
  @classmethod
115
155
  def encode(cls, value: Any) -> bytes:
@@ -185,6 +185,8 @@ def cache(
185
185
 
186
186
  if cached is None or (request is not None and request.headers.get("Cache-Control") == "no-cache") : # cache miss
187
187
  result = await ensure_async_func(*args, **kwargs)
188
+ if isinstance(result, Response) and result.status_code >= 400:
189
+ return result
188
190
  to_cache = coder.encode(result)
189
191
 
190
192
  try:
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "fastapi-cache-stable"
3
- version = "0.3.0a0"
3
+ version = "0.3.0a1"
4
4
  description = "Community-maintained, drop-in stable fork of fastapi-cache2"
5
5
  authors = ["Agustin Saiz <agustinsaiz02@gmail.com>"]
6
6
  license = "Apache-2.0"
@@ -18,12 +18,24 @@ classifiers = [
18
18
  "Programming Language :: Python :: 3.9",
19
19
  "Programming Language :: Python :: 3.10",
20
20
  "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
21
23
  "Typing :: Typed",
22
24
  ]
23
25
  packages = [
24
26
  { include = "fastapi_cache" }
25
27
  ]
26
- include = ["LICENSE", "NOTICE", "README.md"]
28
+ include = [
29
+ "LICENSE",
30
+ "NOTICE",
31
+ "README.md",
32
+ "MIGRATION.md",
33
+ "SUPPORT.md",
34
+ "SECURITY.md",
35
+ "CHANGELOG.md",
36
+ "FORK_ORIGIN.md",
37
+ "COMPATIBILITY.md",
38
+ ]
27
39
 
28
40
  [tool.poetry.dependencies]
29
41
  python = "^3.8"
@@ -45,7 +57,7 @@ mypy = { version = "^1.2.0", python = "^3.10" }
45
57
  pyright = { version = "^1.1.373", python = "^3.10" }
46
58
  types-aiobotocore = { extras = ["dynamodb"], version = "^2.5.0.post2", python = "^3.10" }
47
59
  types-redis = { version = "^4.5.4.2", python = "^3.10" }
48
- ruff = { version = ">=0.0.267,<0.1.2", python = "^3.10" }
60
+ ruff = { version = ">=0.17,<0.18", python = "^3.10" }
49
61
 
50
62
  [tool.poetry.group.dev.dependencies]
51
63
  pytest = "*"
@@ -53,7 +65,7 @@ requests = "*"
53
65
  coverage = ">=6.5,<8.0"
54
66
  httpx = "*"
55
67
  tox = "^4.5.1"
56
- towncrier = "^22.12.0"
68
+ towncrier = { version = ">=26,<27", python = ">=3.9" }
57
69
 
58
70
  [tool.poetry.group.distributing]
59
71
  optional = true
@@ -69,7 +81,7 @@ all = ["redis", "aiomcache", "aiobotocore"]
69
81
 
70
82
  [tool.mypy]
71
83
  files = ["."]
72
- python_version = "3.8"
84
+ python_version = "3.10"
73
85
  # equivalent of --strict
74
86
  warn_unused_configs = true
75
87
  disallow_any_generics = true
@@ -97,15 +109,27 @@ package = "fastapi_cache"
97
109
  start_string = "<!-- towncrier release notes start -->\n"
98
110
  underlines = ["", "", ""]
99
111
  template = "changelog.d/changelog_template.jinja"
100
- title_format = "## [{version}](https://github.com/long2ice/fastapi-cache/tree/{version}) - {project_date}"
101
- issue_format = "[#{issue}](https://github.com/long2ice/fastapi-cache/issues/{issue})"
112
+ title_format = "## [{version}](https://github.com/agustin18/fastapi-cache/tree/v{version}) - {project_date}"
113
+ issue_format = "[#{issue}](https://github.com/agustin18/fastapi-cache/issues/{issue})"
102
114
 
103
115
  [tool.pyright]
104
116
  strict = ["fastapi_cache", "tests"]
105
- pythonVersion = "3.8"
117
+ pythonVersion = "3.10"
106
118
 
107
119
  [tool.pytest.ini_options]
108
120
  addopts = "-p no:warnings"
121
+ markers = [
122
+ "redis: integration tests that require a Redis server",
123
+ ]
124
+ testpaths = ["tests"]
125
+
126
+ [tool.coverage.run]
127
+ branch = true
128
+ source = ["fastapi_cache"]
129
+
130
+ [tool.coverage.report]
131
+ show_missing = true
132
+ skip_covered = true
109
133
 
110
134
  [tool.ruff]
111
135
  ignore = ["E501"]
@@ -1,30 +0,0 @@
1
- from typing import Optional, Tuple, Union
2
-
3
- from redis.asyncio.client import Redis
4
- from redis.asyncio.cluster import RedisCluster
5
-
6
- from fastapi_cache.types import Backend
7
-
8
-
9
- class RedisBackend(Backend):
10
- def __init__(self, redis: Union["Redis[bytes]", "RedisCluster[bytes]"]):
11
- self.redis = redis
12
- self.is_cluster: bool = isinstance(redis, RedisCluster)
13
-
14
- async def get_with_ttl(self, key: str) -> Tuple[int, Optional[bytes]]:
15
- async with self.redis.pipeline(transaction=not self.is_cluster) as pipe:
16
- return await pipe.ttl(key).get(key).execute() # type: ignore[union-attr,no-any-return]
17
-
18
- async def get(self, key: str) -> Optional[bytes]:
19
- return await self.redis.get(key) # type: ignore[union-attr]
20
-
21
- async def set(self, key: str, value: bytes, expire: Optional[int] = None) -> None:
22
- await self.redis.set(key, value, ex=expire) # type: ignore[union-attr]
23
-
24
- async def clear(self, namespace: Optional[str] = None, key: Optional[str] = None) -> int:
25
- if namespace:
26
- lua = f"for i, name in ipairs(redis.call('KEYS', '{namespace}:*')) do redis.call('DEL', name); end"
27
- return await self.redis.eval(lua, numkeys=0) # type: ignore[union-attr,no-any-return]
28
- elif key:
29
- return await self.redis.delete(key) # type: ignore[union-attr]
30
- return 0