Skip to content

Commit 5f0dfdb

Browse files
author
JiayuXu
committed
fix: 正确缓存与恢复响应对象
1 parent c3badc8 commit 5f0dfdb

1 file changed

Lines changed: 23 additions & 1 deletion

File tree

src/utils/cache.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import redis.asyncio as redis
77

88
from log import logger
9+
from schemas.base import Fail, Success, SuccessExtra
910
from settings.config import settings
1011

1112

@@ -149,14 +150,35 @@ async def wrapper(*args, **kwargs):
149150
cached_result = await cache_manager.get(cache_key)
150151
if cached_result is not None:
151152
logger.debug(f"缓存命中: {cache_key}")
153+
if isinstance(cached_result, dict) and cached_result.get("__response__"):
154+
response_type = cached_result.get("class")
155+
payload = cached_result.get("payload", {})
156+
response_cls = {
157+
"Success": Success,
158+
"Fail": Fail,
159+
"SuccessExtra": SuccessExtra,
160+
}.get(response_type, Success)
161+
return response_cls(**payload)
152162
return cached_result
153163

154164
# 执行原函数
155165
result = await func(*args, **kwargs)
156166

157167
# 设置缓存
158168
if result is not None:
159-
await cache_manager.set(cache_key, result, ttl)
169+
value_to_cache: Any = result
170+
if isinstance(result, (Success, Fail, SuccessExtra)):
171+
body_bytes = result.body
172+
if isinstance(body_bytes, bytes):
173+
payload = json.loads(body_bytes.decode("utf-8"))
174+
else:
175+
payload = json.loads(body_bytes)
176+
value_to_cache = {
177+
"__response__": True,
178+
"class": result.__class__.__name__,
179+
"payload": payload,
180+
}
181+
await cache_manager.set(cache_key, value_to_cache, ttl)
160182
logger.debug(f"缓存设置: {cache_key}")
161183

162184
return result

0 commit comments

Comments
 (0)