AI掘金头条新闻系统 (Toutiao News)-缓存新闻详情

1. cache/news_cache.py

python 复制代码
NEWS_DETAIL_PREFIX = "news:detail:"

# 读取缓存-新闻详情 key = news:detail:新闻id
async def get_cached_news_detail(news_id: int) -> Optional[Dict[str, Any]]:
    key = f"{NEWS_DETAIL_PREFIX}{news_id}"
    return await get_json_cache(key)


# 写入缓存-新闻详情 key = news:detail:新闻id + 新闻数据 + 过期时间
async def cache_news_detail(news_id: int, news_data: Dict[str, Any], expire: int = 300) -> bool:
    key = f"{NEWS_DETAIL_PREFIX}{news_id}"
    return await set_cache(key, news_data, expire)

2. 改造crud/news.py

python 复制代码
# 获取新闻详情
async def get_news_detail(
        db: AsyncSession,
        new_id : int
):
    # 先尝试从缓存获取新闻详情
    cached_detail = await get_cached_news_detail(new_id)
    if cached_detail:
        return News(**cached_detail)

    # 查询数据库
    stmt = select(News).where(News.id == new_id)
    result = await db.execute(stmt)
    news = result.scalar_one_or_none()

    # 写入缓存
    if news:
        news_data = jsonable_encoder(news)
        await cache_news_detail(new_id, news_data)

    return news
相关推荐
从零开始学习人工智能15 小时前
【踩坑实录】WSL2 解决 onnxruntime\-gpu ImportError: libcudart\.so\.13 无 CUDA13 运行库问题
python
东风破_16 小时前
ESLint 是什么?为什么你的项目需要它?
前端·后端·代码规范
嘻哈∠※16 小时前
0061基于 SpringBoot 的投稿与稿件处理系统设计与实现
java·spring boot·后端
卷无止境16 小时前
在 awesome-fastapi 里,哪些库值得一看?
后端·python
zhanghaha131416 小时前
Python进阶教程:6_JSON 数据解析 —— 新手完全指南
开发语言·python·json
Python私教17 小时前
API 输出模型怎么设计:从 model_dump() 到显式展示层
python·fastapi
Python私教17 小时前
本地 AI 工具服务该绑定 127.0.0.1 还是 0.0.0.0?
python·fastapi
卷无止境17 小时前
FastAPI 的Admin面板生态
后端·python
ctlover18 小时前
Streamlit 框架
python
ι:18 小时前
MATLAB 与 Python 搭建无人机地面站:优势、劣势与选型逻辑
python·matlab·无人机