fastapi-cachex 0.3.7__tar.gz → 0.3.9__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 (47) hide show
  1. fastapi_cachex-0.3.9/LICENSE +201 -0
  2. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/PKG-INFO +43 -18
  3. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/README.md +32 -12
  4. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/__init__.py +16 -0
  5. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/backends/base.py +104 -6
  6. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/backends/codec.py +21 -7
  7. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/backends/config.py +8 -1
  8. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/backends/memcached.py +238 -66
  9. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/backends/memory.py +107 -24
  10. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/backends/redis.py +252 -50
  11. fastapi_cachex-0.3.9/fastapi_cachex/cache.py +1458 -0
  12. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/dependencies.py +13 -21
  13. fastapi_cachex-0.3.9/fastapi_cachex/exceptions.py +58 -0
  14. fastapi_cachex-0.3.9/fastapi_cachex/headers.py +27 -0
  15. fastapi_cachex-0.3.9/fastapi_cachex/lock.py +203 -0
  16. fastapi_cachex-0.3.9/fastapi_cachex/manager.py +581 -0
  17. fastapi_cachex-0.3.9/fastapi_cachex/proxy.py +174 -0
  18. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/routes.py +82 -23
  19. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/session/__init__.py +6 -0
  20. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/session/config.py +101 -4
  21. fastapi_cachex-0.3.9/fastapi_cachex/session/dependencies.py +386 -0
  22. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/session/exceptions.py +8 -2
  23. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/session/manager.py +74 -20
  24. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/session/middleware.py +355 -75
  25. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/session/token_serializers.py +45 -2
  26. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/state/dependencies.py +8 -9
  27. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/state/exceptions.py +1 -1
  28. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/state/manager.py +71 -11
  29. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/state/models.py +7 -0
  30. fastapi_cachex-0.3.9/fastapi_cachex/types.py +130 -0
  31. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/pyproject.toml +37 -14
  32. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/pyproject.toml.orig +48 -15
  33. fastapi_cachex-0.3.7/fastapi_cachex/cache.py +0 -734
  34. fastapi_cachex-0.3.7/fastapi_cachex/exceptions.py +0 -17
  35. fastapi_cachex-0.3.7/fastapi_cachex/manager.py +0 -253
  36. fastapi_cachex-0.3.7/fastapi_cachex/proxy.py +0 -124
  37. fastapi_cachex-0.3.7/fastapi_cachex/session/dependencies.py +0 -166
  38. fastapi_cachex-0.3.7/fastapi_cachex/types.py +0 -73
  39. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/backends/__init__.py +0 -0
  40. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/directives.py +0 -0
  41. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/manager_proxy.py +0 -0
  42. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/py.typed +0 -0
  43. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/session/models.py +0 -0
  44. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/session/proxy.py +0 -0
  45. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/session/security.py +0 -0
  46. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/state/__init__.py +0 -0
  47. {fastapi_cachex-0.3.7 → fastapi_cachex-0.3.9}/fastapi_cachex/state/proxy.py +0 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025-2026 allen0099
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -1,11 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fastapi-cachex
3
- Version: 0.3.7
3
+ Version: 0.3.9
4
4
  Summary: A caching library for FastAPI with support for Cache-Control, ETag, and multiple backends.
5
5
  Keywords: fastapi,cache,etag,cache-control,redis,memcached,in-memory
6
6
  Author: allen0099
7
7
  Author-email: allen0099 <s96016641@gmail.com>
8
8
  License-Expression: Apache-2.0
9
+ License-File: LICENSE
9
10
  Classifier: Development Status :: 3 - Alpha
10
11
  Classifier: Intended Audience :: Developers
11
12
  Classifier: Programming Language :: Python
@@ -19,13 +20,16 @@ Classifier: Programming Language :: Python :: 3 :: Only
19
20
  Classifier: Framework :: FastAPI
20
21
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
22
  Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
22
- Requires-Dist: fastapi
23
- Requires-Dist: itsdangerous
24
- Requires-Dist: pydantic
23
+ Classifier: Typing :: Typed
24
+ Requires-Dist: fastapi>=0.133.0
25
+ Requires-Dist: itsdangerous>=1.1.0
26
+ Requires-Dist: pydantic>=2.7.0
27
+ Requires-Dist: starlette>=1.0.0
25
28
  Requires-Dist: pyjwt>=2.9.0 ; extra == 'jwt'
26
- Requires-Dist: pymemcache ; extra == 'memcache'
29
+ Requires-Dist: pymemcache>=4.0.0 ; extra == 'memcache'
30
+ Requires-Dist: pymemcache>=4.0.0 ; extra == 'memcached'
27
31
  Requires-Dist: redis[hiredis]>=5.3.0 ; extra == 'redis'
28
- Requires-Dist: orjson ; extra == 'redis'
32
+ Requires-Dist: orjson>=3.4.7 ; extra == 'redis'
29
33
  Requires-Python: >=3.10
30
34
  Project-URL: Homepage, https://github.com/allen0099/FastAPI-CacheX
31
35
  Project-URL: Repository, https://github.com/allen0099/FastAPI-CacheX.git
@@ -33,6 +37,7 @@ Project-URL: Issues, https://github.com/allen0099/FastAPI-CacheX/issues
33
37
  Project-URL: Documentation, https://fastapi-cachex.readthedocs.io/
34
38
  Provides-Extra: jwt
35
39
  Provides-Extra: memcache
40
+ Provides-Extra: memcached
36
41
  Provides-Extra: redis
37
42
  Description-Content-Type: text/markdown
38
43
 
@@ -43,14 +48,14 @@ Description-Content-Type: text/markdown
43
48
  [![Tests](https://github.com/allen0099/FastAPI-CacheX/actions/workflows/test.yml/badge.svg)](https://github.com/allen0099/FastAPI-CacheX/actions/workflows/test.yml)
44
49
  [![Coverage Status](https://raw.githubusercontent.com/allen0099/FastAPI-CacheX/coverage-badge/coverage.svg)](https://github.com/allen0099/FastAPI-CacheX/actions/workflows/coverage.yml)
45
50
 
46
- [![Downloads](https://static.pepy.tech/badge/fastapi-cachex)](https://pepy.tech/project/fastapi-cachex)
47
- [![Weekly downloads](https://static.pepy.tech/badge/fastapi-cachex/week)](https://pepy.tech/project/fastapi-cachex)
48
- [![Monthly downloads](https://static.pepy.tech/badge/fastapi-cachex/month)](https://pepy.tech/project/fastapi-cachex)
51
+ [![Downloads](https://static.pepy.tech/badge/fastapi-cachex)](https://pepy.tech/projects/fastapi-cachex)
52
+ [![Weekly downloads](https://static.pepy.tech/badge/fastapi-cachex/week)](https://pepy.tech/projects/fastapi-cachex)
53
+ [![Monthly downloads](https://static.pepy.tech/badge/fastapi-cachex/month)](https://pepy.tech/projects/fastapi-cachex)
49
54
 
50
55
  [![PyPI version](https://img.shields.io/pypi/v/fastapi-cachex.svg?logo=pypi&logoColor=gold&label=PyPI)](https://pypi.org/project/fastapi-cachex)
51
56
  [![Python Versions](https://img.shields.io/pypi/pyversions/fastapi-cachex.svg?logo=python&label=Python&logoColor=gold)](https://pypi.org/project/fastapi-cachex/)
52
57
 
53
- [English](https://github.com/allen0099/FastAPI-CacheX/blob/master/README.md) | [繁體中文](https://github.com/allen0099/FastAPI-CacheX/blob/master/i18n/zh-TW/docs/index.md)
58
+ [English](https://fastapi-cachex.readthedocs.io/en/latest/) | [繁體中文](https://fastapi-cachex.readthedocs.io/zh-tw/latest/)
54
59
 
55
60
  A high-performance caching extension for FastAPI: a server-side response cache with `Cache-Control` and `ETag` support, application-level caching, and optional session management.
56
61
 
@@ -80,7 +85,7 @@ backends and the optional session transports ship as extras:
80
85
  | Extra | Install | Pulls in | Needed for |
81
86
  |-------|---------|----------|------------|
82
87
  | `redis` | `uv add "fastapi-cachex[redis]"` | `redis[hiredis]`, `orjson` | `AsyncRedisCacheBackend` |
83
- | `memcache` | `uv add "fastapi-cachex[memcache]"` | `pymemcache` | `MemcachedBackend` (note: `memcache`, not `memcached`) |
88
+ | `memcached` | `uv add "fastapi-cachex[memcached]"` | `pymemcache` | `MemcachedBackend` (the older `memcache` name still works until 0.4.0) |
84
89
  | `jwt` | `uv add "fastapi-cachex[jwt]"` | `PyJWT` | `SessionConfig(token_format="jwt")` |
85
90
 
86
91
  Extras combine: `uv add "fastapi-cachex[redis,jwt]"`.
@@ -109,25 +114,45 @@ def build_report() -> dict:
109
114
 
110
115
  @app.get("/report")
111
116
  async def report(cache: AppCache):
112
- # Cache any JSON value in your own code.
113
- return await cache.get_or_set("report", build_report, ttl=300)
117
+ # Cache any JSON value in your own code. lock=True runs build_report once
118
+ # for concurrent misses (the default from 0.4.0).
119
+ return await cache.get_or_set("report", build_report, ttl=300, lock=True)
114
120
  ```
115
121
 
122
+ > [!IMPORTANT]
123
+ > Put `@cache` **below** the route decorator. FastAPI registers whatever function
124
+ > reaches `@app.get(...)`; with `@cache` on top, FastAPI registers the
125
+ > undecorated handler, so the route works but nothing is cached and nothing warns
126
+ > (see [Decorator order](https://fastapi-cachex.readthedocs.io/en/latest/HTTP_CACHING/#decorator-order)).
127
+ >
128
+ > ```python
129
+ > @app.get("/items") # ✅ route decorator first,
130
+ > @cache(ttl=60) # @cache directly above the function
131
+ > async def items(): ...
132
+ >
133
+ > @cache(ttl=60) # ❌ never called: nothing is cached
134
+ > @app.get("/items")
135
+ > async def items(): ...
136
+ > ```
137
+
116
138
  > [!WARNING]
117
139
  > The default cache key carries no user identity. Cache authenticated endpoints
118
- > with `private=True` or a per-user key builder — see
140
+ > with `private=True` or a per-user key builder plus `cache_authorized=True`
141
+ > (requests with `Authorization` or a session otherwise bypass the backend) — see
119
142
  > [Authenticated endpoints](https://fastapi-cachex.readthedocs.io/en/latest/HTTP_CACHING/#authenticated-endpoints).
120
143
 
121
144
  ## Documentation
122
145
 
146
+ - [Migrating to 0.4.0](https://fastapi-cachex.readthedocs.io/en/latest/MIGRATING_0_4/) — what 0.4.0 changes and how to act on the 0.3.9 warnings now
123
147
  - [HTTP caching](https://fastapi-cachex.readthedocs.io/en/latest/HTTP_CACHING/) — the `@cache` decorator, Cache-Control directives, cache keys, invalidation and monitoring routes
124
- - [Cache flow](https://fastapi-cachex.readthedocs.io/en/latest/CACHE_FLOW/) — what happens inside a cached request
125
148
  - [Application cache](https://fastapi-cachex.readthedocs.io/en/latest/APP_CACHE/) — `CacheManager`
126
149
  - [Backends](https://fastapi-cachex.readthedocs.io/en/latest/BACKENDS/) — choosing and configuring a backend, atomic primitives
127
- - [Session management](https://fastapi-cachex.readthedocs.io/en/latest/SESSION/) and [JWT claims](https://fastapi-cachex.readthedocs.io/en/latest/JWT_CLAIMS/)
128
- - [OAuth state](https://fastapi-cachex.readthedocs.io/en/latest/STATE/) — one-shot OAuth/CSRF state tokens
150
+ - [Distributed lock](https://fastapi-cachex.readthedocs.io/en/latest/LOCK/) — `CacheLock` for multi-process mutual exclusion
151
+ - [Session management](https://fastapi-cachex.readthedocs.io/en/latest/SESSION/), [OAuth state](https://fastapi-cachex.readthedocs.io/en/latest/STATE/) (one-shot OAuth/CSRF state tokens) and [JWT claims](https://fastapi-cachex.readthedocs.io/en/latest/JWT_CLAIMS/)
152
+ - [Cache flow](https://fastapi-cachex.readthedocs.io/en/latest/CACHE_FLOW/) — what happens inside a cached request
153
+ - [Runnable examples](https://github.com/allen0099/FastAPI-CacheX/tree/master/examples) — one complete app per feature, each covered by the test suite
129
154
  - [API reference](https://fastapi-cachex.readthedocs.io/en/latest/api/http-caching/)
130
- - [Development guide](https://fastapi-cachex.readthedocs.io/en/latest/DEVELOPMENT/) and [contributing](https://fastapi-cachex.readthedocs.io/en/latest/CONTRIBUTING/)
155
+ - [Development guide](https://fastapi-cachex.readthedocs.io/en/latest/DEVELOPMENT/) and [contributing](https://fastapi-cachex.readthedocs.io/en/latest/CONTRIBUTING/) · [Security policy](https://github.com/allen0099/FastAPI-CacheX/blob/master/SECURITY.md) — report vulnerabilities privately, not in public issues
131
156
  - [Changelog](https://github.com/allen0099/FastAPI-CacheX/blob/master/CHANGELOG.md) · [Known limitations and planned work](https://github.com/allen0099/FastAPI-CacheX/issues)
132
157
 
133
158
  ## License
@@ -5,14 +5,14 @@
5
5
  [![Tests](https://github.com/allen0099/FastAPI-CacheX/actions/workflows/test.yml/badge.svg)](https://github.com/allen0099/FastAPI-CacheX/actions/workflows/test.yml)
6
6
  [![Coverage Status](https://raw.githubusercontent.com/allen0099/FastAPI-CacheX/coverage-badge/coverage.svg)](https://github.com/allen0099/FastAPI-CacheX/actions/workflows/coverage.yml)
7
7
 
8
- [![Downloads](https://static.pepy.tech/badge/fastapi-cachex)](https://pepy.tech/project/fastapi-cachex)
9
- [![Weekly downloads](https://static.pepy.tech/badge/fastapi-cachex/week)](https://pepy.tech/project/fastapi-cachex)
10
- [![Monthly downloads](https://static.pepy.tech/badge/fastapi-cachex/month)](https://pepy.tech/project/fastapi-cachex)
8
+ [![Downloads](https://static.pepy.tech/badge/fastapi-cachex)](https://pepy.tech/projects/fastapi-cachex)
9
+ [![Weekly downloads](https://static.pepy.tech/badge/fastapi-cachex/week)](https://pepy.tech/projects/fastapi-cachex)
10
+ [![Monthly downloads](https://static.pepy.tech/badge/fastapi-cachex/month)](https://pepy.tech/projects/fastapi-cachex)
11
11
 
12
12
  [![PyPI version](https://img.shields.io/pypi/v/fastapi-cachex.svg?logo=pypi&logoColor=gold&label=PyPI)](https://pypi.org/project/fastapi-cachex)
13
13
  [![Python Versions](https://img.shields.io/pypi/pyversions/fastapi-cachex.svg?logo=python&label=Python&logoColor=gold)](https://pypi.org/project/fastapi-cachex/)
14
14
 
15
- [English](https://github.com/allen0099/FastAPI-CacheX/blob/master/README.md) | [繁體中文](https://github.com/allen0099/FastAPI-CacheX/blob/master/i18n/zh-TW/docs/index.md)
15
+ [English](https://fastapi-cachex.readthedocs.io/en/latest/) | [繁體中文](https://fastapi-cachex.readthedocs.io/zh-tw/latest/)
16
16
 
17
17
  A high-performance caching extension for FastAPI: a server-side response cache with `Cache-Control` and `ETag` support, application-level caching, and optional session management.
18
18
 
@@ -42,7 +42,7 @@ backends and the optional session transports ship as extras:
42
42
  | Extra | Install | Pulls in | Needed for |
43
43
  |-------|---------|----------|------------|
44
44
  | `redis` | `uv add "fastapi-cachex[redis]"` | `redis[hiredis]`, `orjson` | `AsyncRedisCacheBackend` |
45
- | `memcache` | `uv add "fastapi-cachex[memcache]"` | `pymemcache` | `MemcachedBackend` (note: `memcache`, not `memcached`) |
45
+ | `memcached` | `uv add "fastapi-cachex[memcached]"` | `pymemcache` | `MemcachedBackend` (the older `memcache` name still works until 0.4.0) |
46
46
  | `jwt` | `uv add "fastapi-cachex[jwt]"` | `PyJWT` | `SessionConfig(token_format="jwt")` |
47
47
 
48
48
  Extras combine: `uv add "fastapi-cachex[redis,jwt]"`.
@@ -71,25 +71,45 @@ def build_report() -> dict:
71
71
 
72
72
  @app.get("/report")
73
73
  async def report(cache: AppCache):
74
- # Cache any JSON value in your own code.
75
- return await cache.get_or_set("report", build_report, ttl=300)
74
+ # Cache any JSON value in your own code. lock=True runs build_report once
75
+ # for concurrent misses (the default from 0.4.0).
76
+ return await cache.get_or_set("report", build_report, ttl=300, lock=True)
76
77
  ```
77
78
 
79
+ > [!IMPORTANT]
80
+ > Put `@cache` **below** the route decorator. FastAPI registers whatever function
81
+ > reaches `@app.get(...)`; with `@cache` on top, FastAPI registers the
82
+ > undecorated handler, so the route works but nothing is cached and nothing warns
83
+ > (see [Decorator order](https://fastapi-cachex.readthedocs.io/en/latest/HTTP_CACHING/#decorator-order)).
84
+ >
85
+ > ```python
86
+ > @app.get("/items") # ✅ route decorator first,
87
+ > @cache(ttl=60) # @cache directly above the function
88
+ > async def items(): ...
89
+ >
90
+ > @cache(ttl=60) # ❌ never called: nothing is cached
91
+ > @app.get("/items")
92
+ > async def items(): ...
93
+ > ```
94
+
78
95
  > [!WARNING]
79
96
  > The default cache key carries no user identity. Cache authenticated endpoints
80
- > with `private=True` or a per-user key builder — see
97
+ > with `private=True` or a per-user key builder plus `cache_authorized=True`
98
+ > (requests with `Authorization` or a session otherwise bypass the backend) — see
81
99
  > [Authenticated endpoints](https://fastapi-cachex.readthedocs.io/en/latest/HTTP_CACHING/#authenticated-endpoints).
82
100
 
83
101
  ## Documentation
84
102
 
103
+ - [Migrating to 0.4.0](https://fastapi-cachex.readthedocs.io/en/latest/MIGRATING_0_4/) — what 0.4.0 changes and how to act on the 0.3.9 warnings now
85
104
  - [HTTP caching](https://fastapi-cachex.readthedocs.io/en/latest/HTTP_CACHING/) — the `@cache` decorator, Cache-Control directives, cache keys, invalidation and monitoring routes
86
- - [Cache flow](https://fastapi-cachex.readthedocs.io/en/latest/CACHE_FLOW/) — what happens inside a cached request
87
105
  - [Application cache](https://fastapi-cachex.readthedocs.io/en/latest/APP_CACHE/) — `CacheManager`
88
106
  - [Backends](https://fastapi-cachex.readthedocs.io/en/latest/BACKENDS/) — choosing and configuring a backend, atomic primitives
89
- - [Session management](https://fastapi-cachex.readthedocs.io/en/latest/SESSION/) and [JWT claims](https://fastapi-cachex.readthedocs.io/en/latest/JWT_CLAIMS/)
90
- - [OAuth state](https://fastapi-cachex.readthedocs.io/en/latest/STATE/) — one-shot OAuth/CSRF state tokens
107
+ - [Distributed lock](https://fastapi-cachex.readthedocs.io/en/latest/LOCK/) — `CacheLock` for multi-process mutual exclusion
108
+ - [Session management](https://fastapi-cachex.readthedocs.io/en/latest/SESSION/), [OAuth state](https://fastapi-cachex.readthedocs.io/en/latest/STATE/) (one-shot OAuth/CSRF state tokens) and [JWT claims](https://fastapi-cachex.readthedocs.io/en/latest/JWT_CLAIMS/)
109
+ - [Cache flow](https://fastapi-cachex.readthedocs.io/en/latest/CACHE_FLOW/) — what happens inside a cached request
110
+ - [Runnable examples](https://github.com/allen0099/FastAPI-CacheX/tree/master/examples) — one complete app per feature, each covered by the test suite
91
111
  - [API reference](https://fastapi-cachex.readthedocs.io/en/latest/api/http-caching/)
92
- - [Development guide](https://fastapi-cachex.readthedocs.io/en/latest/DEVELOPMENT/) and [contributing](https://fastapi-cachex.readthedocs.io/en/latest/CONTRIBUTING/)
112
+ - [Development guide](https://fastapi-cachex.readthedocs.io/en/latest/DEVELOPMENT/) and [contributing](https://fastapi-cachex.readthedocs.io/en/latest/CONTRIBUTING/) · [Security policy](https://github.com/allen0099/FastAPI-CacheX/blob/master/SECURITY.md) — report vulnerabilities privately, not in public issues
93
113
  - [Changelog](https://github.com/allen0099/FastAPI-CacheX/blob/master/CHANGELOG.md) · [Known limitations and planned work](https://github.com/allen0099/FastAPI-CacheX/issues)
94
114
 
95
115
  ## License
@@ -4,6 +4,7 @@ import logging
4
4
  from importlib.metadata import PackageNotFoundError
5
5
  from importlib.metadata import version
6
6
 
7
+ from .cache import build_cache_key as build_cache_key
7
8
  from .cache import cache as cache
8
9
  from .cache import default_key_builder as default_key_builder
9
10
  from .cache import invalidate as invalidate
@@ -11,6 +12,12 @@ from .dependencies import AppCache as AppCache
11
12
  from .dependencies import CacheBackend as CacheBackend
12
13
  from .dependencies import get_app_cache as get_app_cache
13
14
  from .dependencies import get_cache_backend as get_cache_backend
15
+ from .exceptions import BackendNotFoundError as BackendNotFoundError
16
+ from .exceptions import CacheXError as CacheXError
17
+ from .exceptions import LockTimeoutError as LockTimeoutError
18
+ from .exceptions import ProxyNotSetError as ProxyNotSetError
19
+ from .exceptions import RequestNotFoundError as RequestNotFoundError
20
+ from .lock import CacheLock as CacheLock
14
21
  from .manager import CacheManager as CacheManager
15
22
  from .manager_proxy import CacheManagerProxy as CacheManagerProxy
16
23
  from .proxy import BackendProxy as BackendProxy
@@ -26,6 +33,7 @@ from .session import get_optional_session as get_optional_session
26
33
  from .session import get_session as get_session
27
34
  from .session import get_session_manager as get_session_manager
28
35
  from .session import require_session as require_session
36
+ from .session import require_user_session as require_user_session
29
37
  from .session.exceptions import SessionError as SessionError
30
38
  from .session.exceptions import SessionExpiredError as SessionExpiredError
31
39
  from .session.exceptions import SessionInvalidError as SessionInvalidError
@@ -66,13 +74,19 @@ _package_logger.addHandler(
66
74
 
67
75
  __all__ = [
68
76
  "AppCache",
77
+ "BackendNotFoundError",
69
78
  "BackendProxy",
70
79
  "CacheBackend",
71
80
  "CacheKeyBuilder",
81
+ "CacheLock",
72
82
  "CacheManager",
73
83
  "CacheManagerProxy",
84
+ "CacheXError",
74
85
  "FastAPICacheXSessionMiddleware",
75
86
  "InvalidStateError",
87
+ "LockTimeoutError",
88
+ "ProxyNotSetError",
89
+ "RequestNotFoundError",
76
90
  "Session",
77
91
  "SessionConfig",
78
92
  "SessionError",
@@ -94,6 +108,7 @@ __all__ = [
94
108
  "StateManagerProxy",
95
109
  "__version__",
96
110
  "add_routes",
111
+ "build_cache_key",
97
112
  "cache",
98
113
  "default_key_builder",
99
114
  "get_app_cache",
@@ -104,4 +119,5 @@ __all__ = [
104
119
  "get_state_manager",
105
120
  "invalidate",
106
121
  "require_session",
122
+ "require_user_session",
107
123
  ]
@@ -4,6 +4,8 @@ import warnings
4
4
  from abc import ABC
5
5
  from abc import abstractmethod
6
6
  from collections.abc import Iterable
7
+ from types import TracebackType
8
+ from typing import TYPE_CHECKING
7
9
  from typing import Any
8
10
 
9
11
  from fastapi_cachex.types import CACHE_KEY_SEPARATOR
@@ -11,6 +13,11 @@ from fastapi_cachex.types import CacheEntry
11
13
  from fastapi_cachex.types import counter_entry
12
14
  from fastapi_cachex.types import counter_value
13
15
 
16
+ if TYPE_CHECKING:
17
+ # Type-only: typing.Self is 3.11+, and typing_extensions is not a runtime
18
+ # dependency.
19
+ from typing_extensions import Self
20
+
14
21
 
15
22
  def warn_if_path_shaped(pattern: str, cleared: int) -> None:
16
23
  """Warn when a ``clear_pattern`` that cleared nothing was written as a path.
@@ -35,6 +42,10 @@ def warn_if_path_shaped(pattern: str, cleared: int) -> None:
35
42
  )
36
43
 
37
44
 
45
+ # The largest TTL accepted anywhere: 2**31 - 1 seconds, about 68 years.
46
+ MAX_TTL = 2**31 - 1
47
+
48
+
38
49
  def validate_ttl(ttl: int | None) -> int | None:
39
50
  """Return ``ttl`` if it is ``None`` or a positive number of seconds.
40
51
 
@@ -43,17 +54,75 @@ def validate_ttl(ttl: int | None) -> int | None:
43
54
  entry at once), so the library refuses them instead of letting the
44
55
  meaning depend on the backend. ``None`` is the way to say "no expiry".
45
56
 
57
+ Only an ``int`` is a TTL. A ``float`` worked on the memory backend and
58
+ failed on Redis and Memcached, and ``True`` passed as one second.
59
+
46
60
  Raises:
47
- ValueError: If ``ttl`` is zero or negative
61
+ TypeError: If ``ttl`` is not an ``int`` (``bool`` included)
62
+ ValueError: If ``ttl`` is zero, negative or larger than ``MAX_TTL``
48
63
  """
49
- if ttl is not None and ttl <= 0:
64
+ if ttl is None:
65
+ return None
66
+ if isinstance(ttl, bool) or not isinstance(ttl, int):
67
+ msg = f"ttl must be an int number of seconds or None, got {type(ttl).__name__}"
68
+ raise TypeError(msg)
69
+ if ttl <= 0:
50
70
  msg = f"ttl must be a positive number of seconds or None, got {ttl!r}"
51
71
  raise ValueError(msg)
72
+ if ttl > MAX_TTL:
73
+ msg = f"ttl must be at most {MAX_TTL} seconds (about 68 years)"
74
+ raise ValueError(msg)
52
75
  return ttl
53
76
 
54
77
 
78
+ def validate_delta(delta: int) -> int:
79
+ """Return ``delta`` if it is an ``int`` a counter can be changed by.
80
+
81
+ Redis counters are signed 64-bit integers and Memcached's are unsigned, so
82
+ a delta outside the signed 64-bit range fails on both, where it used to be
83
+ reported as the key not holding a counter.
84
+
85
+ Raises:
86
+ TypeError: If ``delta`` is not an ``int`` (``bool`` included)
87
+ ValueError: If ``delta`` does not fit in a signed 64-bit integer
88
+ """
89
+ if isinstance(delta, bool) or not isinstance(delta, int):
90
+ msg = f"delta must be an int, got {type(delta).__name__}"
91
+ raise TypeError(msg)
92
+ if not -(2**63) <= delta < 2**63:
93
+ msg = "delta must fit in a signed 64-bit integer"
94
+ raise ValueError(msg)
95
+ return delta
96
+
97
+
55
98
  class BaseCacheBackend(ABC):
56
- """Base class for all cache backends."""
99
+ """Base class for all cache backends.
100
+
101
+ Every backend is an async context manager: ``async with`` returns the
102
+ backend itself and calls ``aclose()`` on the way out.
103
+ """
104
+
105
+ async def aclose(self) -> None: # noqa: B027 - a no-op default, not abstract
106
+ """Release what the backend holds open: connections, background tasks.
107
+
108
+ Call it once on shutdown, typically at the end of a FastAPI lifespan.
109
+ It is safe to call more than once. The base implementation does
110
+ nothing, for backends with nothing to release; the built-in backends
111
+ override it.
112
+ """
113
+
114
+ async def __aenter__(self) -> "Self":
115
+ """Return the backend itself."""
116
+ return self
117
+
118
+ async def __aexit__(
119
+ self,
120
+ exc_type: type[BaseException] | None,
121
+ exc_value: BaseException | None,
122
+ traceback: TracebackType | None,
123
+ ) -> None:
124
+ """Close the backend with ``aclose()``."""
125
+ await self.aclose()
57
126
 
58
127
  @abstractmethod
59
128
  async def get(self, key: str) -> CacheEntry | None:
@@ -77,9 +146,8 @@ class BaseCacheBackend(ABC):
77
146
 
78
147
  The base implementation deletes one key at a time and reports how
79
148
  many were attempted, since ``delete`` does not say whether the key
80
- existed. The memory and Redis backends override it with a single
81
- batched operation that counts what was actually removed; Memcached
82
- keeps this per-key loop.
149
+ existed. The built-in backends override it and count what was
150
+ actually removed.
83
151
  """
84
152
  count = 0
85
153
  for key in keys:
@@ -159,6 +227,32 @@ class BaseCacheBackend(ABC):
159
227
  await self.delete(key)
160
228
  return True
161
229
 
230
+ async def expire_if_equals(self, key: str, expected: CacheEntry, ttl: int) -> bool:
231
+ """Update expiry on ``key`` to ``ttl`` seconds only while it still holds ``expected``.
232
+
233
+ Re-setting a lock's TTL with a plain ``set`` is unsafe: if the holder's
234
+ entry expired and someone else claimed the key in the meantime, a plain
235
+ ``set`` overwrites the new holder's entry. Comparing against the value
236
+ the caller stored makes the renewal a no-op in that case.
237
+
238
+ The base implementation is a best-effort, NON-atomic get-compare-set
239
+ fallback for third-party backends; the built-in backends override it
240
+ with an atomic implementation.
241
+
242
+ Args:
243
+ key: Cache key to update expiry for
244
+ expected: The entry the caller stored (compared with ``==``)
245
+ ttl: Time to live in seconds
246
+
247
+ Returns:
248
+ Whether the expiry was updated
249
+ """
250
+ validate_ttl(ttl)
251
+ if await self.get(key) != expected:
252
+ return False
253
+ await self.set(key, expected, ttl=ttl)
254
+ return True
255
+
162
256
  async def increment(self, key: str, delta: int = 1, ttl: int | None = None) -> int:
163
257
  """Atomically add ``delta`` to the integer counter stored at ``key``.
164
258
 
@@ -184,7 +278,11 @@ class BaseCacheBackend(ABC):
184
278
 
185
279
  Raises:
186
280
  CacheXError: If ``key`` holds a cached response instead of a counter
281
+ TypeError: If ``delta`` or ``ttl`` is not an ``int``
282
+ ValueError: If ``ttl`` is out of range, or ``delta`` does not fit
283
+ in a signed 64-bit integer
187
284
  """
285
+ validate_delta(delta)
188
286
  validate_ttl(ttl)
189
287
  current = await self.get(key)
190
288
  value = delta if current is None else counter_value(current) + delta