fad458b2a7
- UIUX 文档:填充 19 个缺口(多主体画像/健康度/AI+看板/增长域/洞察域/创始人端/OODA/助推/商密) - UIUX 文档:插入 6 个新章节(十四~十九),旧章节重编号为二十~三十一,更新目录和交叉引用 - 作业指导书 x5:导航改为 6 域分组,新增 Context Bar/工作模式/Insight Rail/决策线程/多工作区等 UI 概念 - 新建 docs/2-task-uiux.md:50 个代码落地开发任务,按 P0-P6 分优先级 + 8 Sprint 规划 - 后端/前端:大量新增模型、路由、组件(来自之前 Phase 开发)
50 lines
1.3 KiB
Python
50 lines
1.3 KiB
Python
"""缓存装饰器。
|
|
|
|
为热点接口自动添加 Redis 缓存。
|
|
"""
|
|
|
|
import functools
|
|
import hashlib
|
|
import logging
|
|
from typing import Any, Callable
|
|
|
|
from app.core.redis import cache_get, cache_set
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def cached(prefix: str, ttl: int = 300):
|
|
"""缓存装饰器 — 自动缓存函数返回值。
|
|
|
|
Args:
|
|
prefix: 缓存键前缀
|
|
ttl: 缓存过期时间(秒)
|
|
"""
|
|
|
|
def decorator(func: Callable) -> Callable:
|
|
@functools.wraps(func)
|
|
async def wrapper(*args, **kwargs) -> Any:
|
|
# 生成缓存键
|
|
key_parts = [prefix]
|
|
for arg in args[1:]: # 跳过 self/db
|
|
key_parts.append(str(arg))
|
|
for k, v in sorted(kwargs.items()):
|
|
key_parts.append(f"{k}={v}")
|
|
cache_key = hashlib.md5(":".join(key_parts).encode()).hexdigest()
|
|
|
|
# 尝试获取缓存
|
|
cached = await cache_get(f"{prefix}:{cache_key}")
|
|
if cached is not None:
|
|
return cached
|
|
|
|
# 执行函数
|
|
result = await func(*args, **kwargs)
|
|
|
|
# 写入缓存
|
|
await cache_set(f"{prefix}:{cache_key}", result, ttl)
|
|
return result
|
|
|
|
return wrapper
|
|
|
|
return decorator
|