fastapi-cachex 0.1.3__py3-none-any.whl → 0.1.4__py3-none-any.whl

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.

Potentially problematic release.


This version of fastapi-cachex might be problematic. Click here for more details.

fastapi_cachex/cache.py CHANGED
@@ -120,6 +120,43 @@ def cache( # noqa: C901
120
120
  else:
121
121
  request_name = found_request.name
122
122
 
123
+ async def get_cache_control(cache_control: CacheControl) -> str: # noqa: C901
124
+ # Set Cache-Control headers
125
+ if no_cache:
126
+ cache_control.add(DirectiveType.NO_CACHE)
127
+ if must_revalidate:
128
+ cache_control.add(DirectiveType.MUST_REVALIDATE)
129
+ else:
130
+ # Handle normal cache control cases
131
+ # 1. Access scope (public/private)
132
+ if public:
133
+ cache_control.add(DirectiveType.PUBLIC)
134
+ elif private:
135
+ cache_control.add(DirectiveType.PRIVATE)
136
+
137
+ # 2. Cache time settings
138
+ if ttl is not None:
139
+ cache_control.add(DirectiveType.MAX_AGE, ttl)
140
+
141
+ # 3. Validation related
142
+ if must_revalidate:
143
+ cache_control.add(DirectiveType.MUST_REVALIDATE)
144
+
145
+ # 4. Stale response handling
146
+ if stale is not None and stale_ttl is None:
147
+ raise CacheXError("stale_ttl must be set if stale is used")
148
+
149
+ if stale == "revalidate":
150
+ cache_control.add(DirectiveType.STALE_WHILE_REVALIDATE, stale_ttl)
151
+ elif stale == "error":
152
+ cache_control.add(DirectiveType.STALE_IF_ERROR, stale_ttl)
153
+
154
+ # 5. Special flags
155
+ if immutable:
156
+ cache_control.add(DirectiveType.IMMUTABLE)
157
+
158
+ return str(cache_control)
159
+
123
160
  @wraps(func)
124
161
  async def wrapper(*args: Any, **kwargs: Any) -> Response: # noqa: C901
125
162
  if found_request:
@@ -135,79 +172,72 @@ def cache( # noqa: C901
135
172
  if req.method != "GET":
136
173
  return await get_response(func, req, *args, **kwargs)
137
174
 
138
- # Generate cache key
175
+ # Generate cache key and prepare headers
139
176
  cache_key = f"{req.url.path}:{req.query_params}"
140
-
141
- # Check if the data is already in the cache
142
- cached_data = await cache_backend.get(cache_key)
143
-
144
- if cached_data and cached_data.etag == req.headers.get("if-none-match"):
145
- return Response(
146
- status_code=HTTP_304_NOT_MODIFIED,
147
- headers={"ETag": cached_data.etag},
148
- )
149
-
150
- # Get the response
151
- response = await get_response(func, req, *args, **kwargs)
152
-
153
- # Generate ETag (hash based on response content)
154
- etag = f'W/"{hashlib.md5(response.body).hexdigest()}"' # noqa: S324
155
-
156
- # Add ETag to response headers
157
- response.headers["ETag"] = etag
158
-
159
- # Handle Cache-Control header
160
- cache_control = CacheControl()
177
+ client_etag = req.headers.get("if-none-match")
178
+ cache_control = await get_cache_control(CacheControl())
161
179
 
162
180
  # Handle special case: no-store (highest priority)
163
181
  if no_store:
164
- cache_control.add(DirectiveType.NO_STORE)
165
- response.headers["Cache-Control"] = str(cache_control)
182
+ response = await get_response(func, req, *args, **kwargs)
183
+ cc = CacheControl()
184
+ cc.add(DirectiveType.NO_STORE)
185
+ response.headers["Cache-Control"] = str(cc)
166
186
  return response
167
187
 
168
- # Handle special case: no-cache
169
- if no_cache:
170
- cache_control.add(DirectiveType.NO_CACHE)
171
- if must_revalidate:
172
- cache_control.add(DirectiveType.MUST_REVALIDATE)
173
- response.headers["Cache-Control"] = str(cache_control)
174
- return response
188
+ # Check cache and handle ETag validation
189
+ cached_data = await cache_backend.get(cache_key)
175
190
 
176
- # Handle normal cache control cases
177
- # 1. Access scope (public/private)
178
- if public:
179
- cache_control.add(DirectiveType.PUBLIC)
180
- elif private:
181
- cache_control.add(DirectiveType.PRIVATE)
182
-
183
- # 2. Cache time settings
184
- if ttl is not None:
185
- cache_control.add(DirectiveType.MAX_AGE, ttl)
186
-
187
- # 3. Validation related
188
- if must_revalidate:
189
- cache_control.add(DirectiveType.MUST_REVALIDATE)
190
-
191
- # 4. Stale response handling
192
- if stale is not None and stale_ttl is None:
193
- raise CacheXError("stale_ttl must be set if stale is used")
194
-
195
- if stale == "revalidate":
196
- cache_control.add(DirectiveType.STALE_WHILE_REVALIDATE, stale_ttl)
197
- elif stale == "error":
198
- cache_control.add(DirectiveType.STALE_IF_ERROR, stale_ttl)
199
-
200
- # 5. Special flags
201
- if immutable:
202
- cache_control.add(DirectiveType.IMMUTABLE)
203
-
204
- # Store the data in the cache
205
- await cache_backend.set(
206
- cache_key, ETagContent(etag, response.body), ttl=ttl
207
- )
191
+ current_response = None
192
+ current_etag = None
193
+
194
+ if client_etag:
195
+ if no_cache:
196
+ # Get fresh response first if using no-cache
197
+ current_response = await get_response(func, req, *args, **kwargs)
198
+ current_etag = (
199
+ f'W/"{hashlib.md5(current_response.body).hexdigest()}"' # noqa: S324
200
+ )
201
+
202
+ if client_etag == current_etag:
203
+ # For no-cache, compare fresh data with client's ETag
204
+ return Response(
205
+ status_code=HTTP_304_NOT_MODIFIED,
206
+ headers={
207
+ "ETag": current_etag,
208
+ "Cache-Control": cache_control,
209
+ },
210
+ )
211
+
212
+ # Compare with cached ETag
213
+ elif (
214
+ cached_data and client_etag == cached_data.etag
215
+ ): # pragma: no branch
216
+ return Response(
217
+ status_code=HTTP_304_NOT_MODIFIED,
218
+ headers={
219
+ "ETag": cached_data.etag,
220
+ "Cache-Control": cache_control,
221
+ },
222
+ )
223
+
224
+ if not current_response or not current_etag:
225
+ # Retrieve the current response if not already done
226
+ current_response = await get_response(func, req, *args, **kwargs)
227
+ current_etag = f'W/"{hashlib.md5(current_response.body).hexdigest()}"' # noqa: S324
228
+
229
+ # Set ETag header
230
+ current_response.headers["ETag"] = current_etag
231
+
232
+ # Update cache if needed
233
+ if not cached_data or cached_data.etag != current_etag:
234
+ # Store in cache if data changed
235
+ await cache_backend.set(
236
+ cache_key, ETagContent(current_etag, current_response.body), ttl=ttl
237
+ )
208
238
 
209
- response.headers["Cache-Control"] = str(cache_control)
210
- return response
239
+ current_response.headers["Cache-Control"] = cache_control
240
+ return current_response
211
241
 
212
242
  # Update the wrapper with the new signature
213
243
  update_wrapper(wrapper, func)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fastapi-cachex
3
- Version: 0.1.3
3
+ Version: 0.1.4
4
4
  Summary: A caching library for FastAPI with support for Cache-Control, ETag, and multiple backends.
5
5
  Author-email: Allen <s96016641@gmail.com>
6
6
  License-Expression: Apache-2.0
@@ -126,46 +126,10 @@ BackendProxy.set_backend(backend)
126
126
 
127
127
  Redis support is under development and will be available in future releases.
128
128
 
129
- ## Development Guide
129
+ ## Documentation
130
130
 
131
- ### Running Tests
132
-
133
- 1. Run unit tests:
134
-
135
- ```bash
136
- pytest
137
- ```
138
-
139
- 2. Run tests with coverage report:
140
-
141
- ```bash
142
- pytest --cov=fastapi_cachex
143
- ```
144
-
145
- ### Using tox
146
-
147
- tox ensures the code works across different Python versions (3.10-3.13).
148
-
149
- 1. Install all Python versions
150
- 2. Run tox:
151
-
152
- ```bash
153
- tox
154
- ```
155
-
156
- To run for a specific Python version:
157
-
158
- ```bash
159
- tox -e py310 # only run for Python 3.10
160
- ```
161
-
162
- ## Contributing
163
-
164
- 1. Fork the project
165
- 2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
166
- 3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
167
- 4. Push to the branch (`git push origin feature/AmazingFeature`)
168
- 5. Open a Pull Request
131
+ - [Development Guide](docs/DEVELOPMENT.md)
132
+ - [Contributing Guidelines](docs/CONTRIBUTING.md)
169
133
 
170
134
  ## License
171
135
 
@@ -1,5 +1,5 @@
1
1
  fastapi_cachex/__init__.py,sha256=K8zRD7pEOo77Ged7SJQ-BFNMe6Pnz8yM5ePFq97nI_s,82
2
- fastapi_cachex/cache.py,sha256=V6RhNRZuhb4vR9LBk03DJ-HGnOSTpi3uTBms9rFov8E,7587
2
+ fastapi_cachex/cache.py,sha256=b-55IR0kdcVj4yUk8dplqqUy2avW49P-oI01ART9pyU,9174
3
3
  fastapi_cachex/directives.py,sha256=kJCmsbyQ89m6tsWo_c1vVJn3rk0pD5JZaY8xtNLcRh0,530
4
4
  fastapi_cachex/exceptions.py,sha256=coYct4u6uK_pdjetUWDwM5OUCfhql0OkTECynMRUq4M,379
5
5
  fastapi_cachex/proxy.py,sha256=vFShY7_xp4Sh1XU9dJzsBv2ICN8Rtwx6g1qCcCvmdf8,810
@@ -9,8 +9,8 @@ fastapi_cachex/backends/__init__.py,sha256=U65JrCeh1eusklqUfV5yvZGK7Kfy5RctzfVrR
9
9
  fastapi_cachex/backends/base.py,sha256=eGfn0oZNQ8_drNHz4ZtqBVFSxKxEwW8y4ojw5iShgLQ,707
10
10
  fastapi_cachex/backends/memcached.py,sha256=g3184fHpFK7LH1UY9xfzRszBBzqmzeaLG806B5MsZDM,2190
11
11
  fastapi_cachex/backends/memory.py,sha256=7KFSn5e1CvDzflZ5zqUPDQsBf6emcV0ob_tCsLQcDLw,2445
12
- fastapi_cachex-0.1.3.dist-info/licenses/LICENSE,sha256=asJkHbd10YDSnjeAOIlKafh7E_exwtKXY5rA-qc_Mno,11339
13
- fastapi_cachex-0.1.3.dist-info/METADATA,sha256=-aKGoO1RcxqXe5DZepZOJprK-cm0Xo4He_3ESVZGs6k,5224
14
- fastapi_cachex-0.1.3.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
15
- fastapi_cachex-0.1.3.dist-info/top_level.txt,sha256=97FfG5FDycd3hks-_JznEr-5lUOgg8AZd8pqK5imWj0,15
16
- fastapi_cachex-0.1.3.dist-info/RECORD,,
12
+ fastapi_cachex-0.1.4.dist-info/licenses/LICENSE,sha256=asJkHbd10YDSnjeAOIlKafh7E_exwtKXY5rA-qc_Mno,11339
13
+ fastapi_cachex-0.1.4.dist-info/METADATA,sha256=6qK6F6Pi338JYWN0NEv5SnR8gN4eJaXyFntNmFAu57s,4669
14
+ fastapi_cachex-0.1.4.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
15
+ fastapi_cachex-0.1.4.dist-info/top_level.txt,sha256=97FfG5FDycd3hks-_JznEr-5lUOgg8AZd8pqK5imWj0,15
16
+ fastapi_cachex-0.1.4.dist-info/RECORD,,