fastapi-cachex 0.3.6__tar.gz → 0.3.8__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 (42) hide show
  1. fastapi_cachex-0.3.8/LICENSE +201 -0
  2. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/PKG-INFO +20 -13
  3. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/README.md +9 -7
  4. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/__init__.py +14 -0
  5. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/backends/base.py +92 -3
  6. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/backends/codec.py +11 -9
  7. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/backends/memcached.py +176 -55
  8. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/backends/memory.py +108 -23
  9. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/backends/redis.py +192 -38
  10. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/cache.py +259 -76
  11. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/dependencies.py +13 -21
  12. fastapi_cachex-0.3.8/fastapi_cachex/exceptions.py +58 -0
  13. fastapi_cachex-0.3.8/fastapi_cachex/lock.py +200 -0
  14. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/manager.py +62 -14
  15. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/proxy.py +59 -20
  16. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/routes.py +53 -21
  17. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/session/__init__.py +8 -0
  18. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/session/config.py +85 -3
  19. fastapi_cachex-0.3.8/fastapi_cachex/session/dependencies.py +245 -0
  20. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/session/exceptions.py +8 -2
  21. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/session/manager.py +82 -28
  22. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/session/middleware.py +179 -65
  23. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/session/token_serializers.py +26 -0
  24. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/state/dependencies.py +8 -9
  25. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/state/manager.py +100 -17
  26. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/state/models.py +7 -0
  27. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/types.py +43 -6
  28. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/pyproject.toml +38 -15
  29. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/pyproject.toml.orig +49 -16
  30. fastapi_cachex-0.3.6/fastapi_cachex/exceptions.py +0 -17
  31. fastapi_cachex-0.3.6/fastapi_cachex/session/dependencies.py +0 -125
  32. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/backends/__init__.py +0 -0
  33. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/backends/config.py +0 -0
  34. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/directives.py +0 -0
  35. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/manager_proxy.py +0 -0
  36. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/py.typed +0 -0
  37. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/session/models.py +0 -0
  38. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/session/proxy.py +0 -0
  39. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/session/security.py +0 -0
  40. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/state/__init__.py +0 -0
  41. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/fastapi_cachex/state/exceptions.py +0 -0
  42. {fastapi_cachex-0.3.6 → fastapi_cachex-0.3.8}/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.6
3
+ Version: 0.3.8
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,16 +48,16 @@ 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/docs/README.zh-TW.md)
58
+ [English](https://fastapi-cachex.readthedocs.io/en/latest/) | [繁體中文](https://fastapi-cachex.readthedocs.io/zh-tw/latest/)
54
59
 
55
- A high-performance caching extension for FastAPI, providing comprehensive HTTP caching support and optional session management.
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
 
57
62
  **Documentation:** <https://fastapi-cachex.readthedocs.io/en/latest/> — guides and the full API reference.
58
63
 
@@ -61,7 +66,7 @@ A high-performance caching extension for FastAPI, providing comprehensive HTTP c
61
66
  - **HTTP caching** — a `@cache` decorator for GET routes with `Cache-Control`,
62
67
  `ETag` / `If-None-Match` (304) and per-route invalidation.
63
68
  - **Application cache** — `CacheManager` for caching arbitrary JSON values in
64
- your own code, with compute-on-miss `get_or_set()`.
69
+ your own code, with compute-on-miss `get_or_set()` and atomic store-if-absent `add()`.
65
70
  - **Backends** — in-memory, Redis and Memcached, with atomic counters,
66
71
  one-shot values and locks.
67
72
  - **Sessions (optional)** — HMAC-signed or JWT session tokens over headers,
@@ -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]"`.
@@ -126,6 +131,8 @@ async def report(cache: AppCache):
126
131
  - [Backends](https://fastapi-cachex.readthedocs.io/en/latest/BACKENDS/) — choosing and configuring a backend, atomic primitives
127
132
  - [Session management](https://fastapi-cachex.readthedocs.io/en/latest/SESSION/) and [JWT claims](https://fastapi-cachex.readthedocs.io/en/latest/JWT_CLAIMS/)
128
133
  - [OAuth state](https://fastapi-cachex.readthedocs.io/en/latest/STATE/) — one-shot OAuth/CSRF state tokens
134
+ - [Distributed lock](https://fastapi-cachex.readthedocs.io/en/latest/LOCK/) — `CacheLock` for multi-process mutual exclusion
135
+ - [Runnable examples](https://github.com/allen0099/FastAPI-CacheX/tree/master/examples) — one complete app per feature, each covered by the test suite
129
136
  - [API reference](https://fastapi-cachex.readthedocs.io/en/latest/api/http-caching/)
130
137
  - [Development guide](https://fastapi-cachex.readthedocs.io/en/latest/DEVELOPMENT/) and [contributing](https://fastapi-cachex.readthedocs.io/en/latest/CONTRIBUTING/)
131
138
  - [Changelog](https://github.com/allen0099/FastAPI-CacheX/blob/master/CHANGELOG.md) · [Known limitations and planned work](https://github.com/allen0099/FastAPI-CacheX/issues)
@@ -5,16 +5,16 @@
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/docs/README.zh-TW.md)
15
+ [English](https://fastapi-cachex.readthedocs.io/en/latest/) | [繁體中文](https://fastapi-cachex.readthedocs.io/zh-tw/latest/)
16
16
 
17
- A high-performance caching extension for FastAPI, providing comprehensive HTTP caching support and optional session management.
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
 
19
19
  **Documentation:** <https://fastapi-cachex.readthedocs.io/en/latest/> — guides and the full API reference.
20
20
 
@@ -23,7 +23,7 @@ A high-performance caching extension for FastAPI, providing comprehensive HTTP c
23
23
  - **HTTP caching** — a `@cache` decorator for GET routes with `Cache-Control`,
24
24
  `ETag` / `If-None-Match` (304) and per-route invalidation.
25
25
  - **Application cache** — `CacheManager` for caching arbitrary JSON values in
26
- your own code, with compute-on-miss `get_or_set()`.
26
+ your own code, with compute-on-miss `get_or_set()` and atomic store-if-absent `add()`.
27
27
  - **Backends** — in-memory, Redis and Memcached, with atomic counters,
28
28
  one-shot values and locks.
29
29
  - **Sessions (optional)** — HMAC-signed or JWT session tokens over headers,
@@ -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]"`.
@@ -88,6 +88,8 @@ async def report(cache: AppCache):
88
88
  - [Backends](https://fastapi-cachex.readthedocs.io/en/latest/BACKENDS/) — choosing and configuring a backend, atomic primitives
89
89
  - [Session management](https://fastapi-cachex.readthedocs.io/en/latest/SESSION/) and [JWT claims](https://fastapi-cachex.readthedocs.io/en/latest/JWT_CLAIMS/)
90
90
  - [OAuth state](https://fastapi-cachex.readthedocs.io/en/latest/STATE/) — one-shot OAuth/CSRF state tokens
91
+ - [Distributed lock](https://fastapi-cachex.readthedocs.io/en/latest/LOCK/) — `CacheLock` for multi-process mutual exclusion
92
+ - [Runnable examples](https://github.com/allen0099/FastAPI-CacheX/tree/master/examples) — one complete app per feature, each covered by the test suite
91
93
  - [API reference](https://fastapi-cachex.readthedocs.io/en/latest/api/http-caching/)
92
94
  - [Development guide](https://fastapi-cachex.readthedocs.io/en/latest/DEVELOPMENT/) and [contributing](https://fastapi-cachex.readthedocs.io/en/latest/CONTRIBUTING/)
93
95
  - [Changelog](https://github.com/allen0099/FastAPI-CacheX/blob/master/CHANGELOG.md) · [Known limitations and planned work](https://github.com/allen0099/FastAPI-CacheX/issues)
@@ -11,6 +11,12 @@ from .dependencies import AppCache as AppCache
11
11
  from .dependencies import CacheBackend as CacheBackend
12
12
  from .dependencies import get_app_cache as get_app_cache
13
13
  from .dependencies import get_cache_backend as get_cache_backend
14
+ from .exceptions import BackendNotFoundError as BackendNotFoundError
15
+ from .exceptions import CacheXError as CacheXError
16
+ from .exceptions import LockTimeoutError as LockTimeoutError
17
+ from .exceptions import ProxyNotSetError as ProxyNotSetError
18
+ from .exceptions import RequestNotFoundError as RequestNotFoundError
19
+ from .lock import CacheLock as CacheLock
14
20
  from .manager import CacheManager as CacheManager
15
21
  from .manager_proxy import CacheManagerProxy as CacheManagerProxy
16
22
  from .proxy import BackendProxy as BackendProxy
@@ -26,6 +32,7 @@ from .session import get_optional_session as get_optional_session
26
32
  from .session import get_session as get_session
27
33
  from .session import get_session_manager as get_session_manager
28
34
  from .session import require_session as require_session
35
+ from .session import require_user_session as require_user_session
29
36
  from .session.exceptions import SessionError as SessionError
30
37
  from .session.exceptions import SessionExpiredError as SessionExpiredError
31
38
  from .session.exceptions import SessionInvalidError as SessionInvalidError
@@ -66,13 +73,19 @@ _package_logger.addHandler(
66
73
 
67
74
  __all__ = [
68
75
  "AppCache",
76
+ "BackendNotFoundError",
69
77
  "BackendProxy",
70
78
  "CacheBackend",
71
79
  "CacheKeyBuilder",
80
+ "CacheLock",
72
81
  "CacheManager",
73
82
  "CacheManagerProxy",
83
+ "CacheXError",
74
84
  "FastAPICacheXSessionMiddleware",
75
85
  "InvalidStateError",
86
+ "LockTimeoutError",
87
+ "ProxyNotSetError",
88
+ "RequestNotFoundError",
76
89
  "Session",
77
90
  "SessionConfig",
78
91
  "SessionError",
@@ -104,4 +117,5 @@ __all__ = [
104
117
  "get_state_manager",
105
118
  "invalidate",
106
119
  "require_session",
120
+ "require_user_session",
107
121
  ]
@@ -35,6 +35,59 @@ def warn_if_path_shaped(pattern: str, cleared: int) -> None:
35
35
  )
36
36
 
37
37
 
38
+ # The largest TTL accepted anywhere: 2**31 - 1 seconds, about 68 years.
39
+ MAX_TTL = 2**31 - 1
40
+
41
+
42
+ def validate_ttl(ttl: int | None) -> int | None:
43
+ """Return ``ttl`` if it is ``None`` or a positive number of seconds.
44
+
45
+ Every backend reads ``0`` or a negative TTL differently (Memcached treats
46
+ ``0`` as "never expires", Redis rejects it, the memory backend expires the
47
+ entry at once), so the library refuses them instead of letting the
48
+ meaning depend on the backend. ``None`` is the way to say "no expiry".
49
+
50
+ Only an ``int`` is a TTL. A ``float`` worked on the memory backend and
51
+ failed on Redis and Memcached, and ``True`` passed as one second.
52
+
53
+ Raises:
54
+ TypeError: If ``ttl`` is not an ``int`` (``bool`` included)
55
+ ValueError: If ``ttl`` is zero, negative or larger than ``MAX_TTL``
56
+ """
57
+ if ttl is None:
58
+ return None
59
+ if isinstance(ttl, bool) or not isinstance(ttl, int):
60
+ msg = f"ttl must be an int number of seconds or None, got {type(ttl).__name__}"
61
+ raise TypeError(msg)
62
+ if ttl <= 0:
63
+ msg = f"ttl must be a positive number of seconds or None, got {ttl!r}"
64
+ raise ValueError(msg)
65
+ if ttl > MAX_TTL:
66
+ msg = f"ttl must be at most {MAX_TTL} seconds (about 68 years)"
67
+ raise ValueError(msg)
68
+ return ttl
69
+
70
+
71
+ def validate_delta(delta: int) -> int:
72
+ """Return ``delta`` if it is an ``int`` a counter can be changed by.
73
+
74
+ Redis counters are signed 64-bit integers and Memcached's are unsigned, so
75
+ a delta outside the signed 64-bit range fails on both, where it used to be
76
+ reported as the key not holding a counter.
77
+
78
+ Raises:
79
+ TypeError: If ``delta`` is not an ``int`` (``bool`` included)
80
+ ValueError: If ``delta`` does not fit in a signed 64-bit integer
81
+ """
82
+ if isinstance(delta, bool) or not isinstance(delta, int):
83
+ msg = f"delta must be an int, got {type(delta).__name__}"
84
+ raise TypeError(msg)
85
+ if not -(2**63) <= delta < 2**63:
86
+ msg = "delta must fit in a signed 64-bit integer"
87
+ raise ValueError(msg)
88
+ return delta
89
+
90
+
38
91
  class BaseCacheBackend(ABC):
39
92
  """Base class for all cache backends."""
40
93
 
@@ -44,7 +97,12 @@ class BaseCacheBackend(ABC):
44
97
 
45
98
  @abstractmethod
46
99
  async def set(self, key: str, value: CacheEntry, ttl: int | None = None) -> None:
47
- """Store a response in the cache."""
100
+ """Store a response in the cache.
101
+
102
+ ``ttl`` is ``None`` (never expires) or a positive number of seconds;
103
+ implementations should pass it through ``validate_ttl`` so zero and
104
+ negative values are rejected the same way on every backend.
105
+ """
48
106
 
49
107
  @abstractmethod
50
108
  async def delete(self, key: str) -> None:
@@ -55,8 +113,8 @@ class BaseCacheBackend(ABC):
55
113
 
56
114
  The base implementation deletes one key at a time and reports how
57
115
  many were attempted, since ``delete`` does not say whether the key
58
- existed. The built-in backends override it with a single batched
59
- operation that counts what was actually removed.
116
+ existed. The built-in backends override it and count what was
117
+ actually removed.
60
118
  """
61
119
  count = 0
62
120
  for key in keys:
@@ -106,6 +164,7 @@ class BaseCacheBackend(ABC):
106
164
  Returns:
107
165
  Whether ``value`` was stored
108
166
  """
167
+ validate_ttl(ttl)
109
168
  if await self.get(key) is not None:
110
169
  return False
111
170
  await self.set(key, value, ttl=ttl)
@@ -135,6 +194,32 @@ class BaseCacheBackend(ABC):
135
194
  await self.delete(key)
136
195
  return True
137
196
 
197
+ async def expire_if_equals(self, key: str, expected: CacheEntry, ttl: int) -> bool:
198
+ """Update expiry on ``key`` to ``ttl`` seconds only while it still holds ``expected``.
199
+
200
+ Re-setting a lock's TTL with a plain ``set`` is unsafe: if the holder's
201
+ entry expired and someone else claimed the key in the meantime, a plain
202
+ ``set`` overwrites the new holder's entry. Comparing against the value
203
+ the caller stored makes the renewal a no-op in that case.
204
+
205
+ The base implementation is a best-effort, NON-atomic get-compare-set
206
+ fallback for third-party backends; the built-in backends override it
207
+ with an atomic implementation.
208
+
209
+ Args:
210
+ key: Cache key to update expiry for
211
+ expected: The entry the caller stored (compared with ``==``)
212
+ ttl: Time to live in seconds
213
+
214
+ Returns:
215
+ Whether the expiry was updated
216
+ """
217
+ validate_ttl(ttl)
218
+ if await self.get(key) != expected:
219
+ return False
220
+ await self.set(key, expected, ttl=ttl)
221
+ return True
222
+
138
223
  async def increment(self, key: str, delta: int = 1, ttl: int | None = None) -> int:
139
224
  """Atomically add ``delta`` to the integer counter stored at ``key``.
140
225
 
@@ -160,7 +245,11 @@ class BaseCacheBackend(ABC):
160
245
 
161
246
  Raises:
162
247
  CacheXError: If ``key`` holds a cached response instead of a counter
248
+ TypeError: If ``delta`` or ``ttl`` is not an ``int``
249
+ ValueError: If ``ttl`` is out of range
163
250
  """
251
+ validate_delta(delta)
252
+ validate_ttl(ttl)
164
253
  current = await self.get(key)
165
254
  value = delta if current is None else counter_value(current) + delta
166
255
  await self.set(key, counter_entry(value), ttl=ttl)
@@ -4,9 +4,11 @@ Both backends store a ``CacheEntry`` as a JSON document; ``orjson`` is used when
4
4
  it is installed and the standard library ``json`` module otherwise.
5
5
  """
6
6
 
7
+ from fastapi_cachex.types import COUNTER_FINGERPRINT
7
8
  from fastapi_cachex.types import DEFAULT_STATUS_CODE
8
9
  from fastapi_cachex.types import CacheEntry
9
10
  from fastapi_cachex.types import counter_entry
11
+ from fastapi_cachex.types import parse_counter
10
12
 
11
13
  try:
12
14
  import orjson as json
@@ -27,7 +29,15 @@ def encode_entry(entry: CacheEntry) -> bytes:
27
29
 
28
30
  The raw content bytes are passed through ``latin-1`` so that arbitrary
29
31
  bytes round-trip through JSON text.
32
+
33
+ A counter entry (exactly what ``counter_entry`` builds) is stored as a bare
34
+ integer instead, the form the server-side ``INCR`` family works on, so a
35
+ counter written with ``set()`` can still be passed to ``increment()``.
30
36
  """
37
+ if entry.fingerprint == COUNTER_FINGERPRINT:
38
+ value = parse_counter(entry.content)
39
+ if value is not None and entry == counter_entry(value):
40
+ return entry.content
31
41
  serialized: str | bytes = json.dumps(
32
42
  {
33
43
  "fingerprint": entry.fingerprint,
@@ -41,14 +51,6 @@ def encode_entry(entry: CacheEntry) -> bytes:
41
51
  return serialized if isinstance(serialized, bytes) else serialized.encode("utf-8")
42
52
 
43
53
 
44
- def _as_counter(raw: str | bytes) -> int | None:
45
- """The integer a bare counter value holds, or ``None`` for anything else."""
46
- try:
47
- return int(raw)
48
- except ValueError:
49
- return None
50
-
51
-
52
54
  def decode_entry(raw: str | bytes | None) -> CacheEntry | None:
53
55
  """Rebuild a ``CacheEntry`` from a stored value.
54
56
 
@@ -63,7 +65,7 @@ def decode_entry(raw: str | bytes | None) -> CacheEntry | None:
63
65
  """
64
66
  if raw is None:
65
67
  return None
66
- counter = _as_counter(raw)
68
+ counter = parse_counter(raw)
67
69
  if counter is not None:
68
70
  return counter_entry(counter)
69
71
  try: