收藏添加
添加收藏状态
I.请求与响应过程
当用户进入详情页后,可以点击收藏按钮进行收藏
flowchart LR
subgraph B [后端]
U[FastAPI服务]
end
subgraph A [用户界面]
direction LR
F1[新闻详情]
end
A -- ① 请求分类<br> /api/favorite/add --> B
B -- ② 返回响应 <br> {'code': 200,'message': '收藏成功','data':{'id': 1,'userId': 用户id }} --> A

II. 数据校验模型
当前业务中,检查收藏数据无需校验
III. 路由定义
在favorite.py文件,编写路由解析代码
| @router.post("/add")
async def add_favorite(
data: dict,
authorization: str = Header(...),
db: AsyncSession = Depends(get_db)
):
"""
添加新闻到收藏列表
"""
return {
"code": 200,
"message": "收藏成功",
"data": '用户收藏'
}
|

已经注册过路由
重启FastAPI服务,运行测试,检查定义的路由接口是否能够处理前端发送的请求
post请求可以借助http工具
| ### 添加收藏
POST http://127.0.0.1:8000/api/favorite/add
Content-Type: application/json
Authorization: 24b07f4e-69da-46a5-bb7c-d43603fdf235
{
"newsId": 1
}
|

IV. 定义模型类
模型类已经定义
V. 编写ORM数据操作
在favorite.py文件,将收藏模块的数据操作按照对应的逻辑编写代码
| async def add_favorite(db: AsyncSession, user_id: int, news_id: int) -> Favorite:
"""
添加新闻到收藏列表
Args:
db: 数据库会话
user_id: 用户ID
news_id: 新闻ID
Returns:
dict: 收藏结果
"""
try:
# 创建收藏记录
favorite = Favorite(
user_id=user_id,
news_id=news_id
)
db.add(favorite)
await db.commit()
await db.refresh(favorite)
# 返回成功响应
return favorite
except Exception as e:
await db.rollback()
raise e
|
VI. 路由中实现数据操作
回到对应的路由中,调用刚才编写好的数据处理函数。
| @router.post("/add")
async def add_favorite(
data: dict,
authorization: str = Header(...),
db: AsyncSession = Depends(get_db)
):
"""
添加新闻到收藏列表
"""
try:
# 获取用户token
token = authorization
# 根据令牌获取用户
user = await users.get_user_by_token(db, token)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="无效的认证令牌或令牌已过期"
)
# 添加收藏
result = await favorite.add_favorite(
db, user.id, data.get('newsId')
)
return {
"code": 200,
"message": "收藏成功",
"data": {
"id": result.id,
"userId": result.user_id,
"newsId": result.news_id,
"createTime": result.created_at.isoformat()
}
}
except HTTPException:
raise
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="服务器内部错误"
)
|
重启FastAPI服务,测试数据是否正常返回

前端验证
