源码见:"fastapi_study_road-learning_system_online_courses: fastapi框架实战之--在线课程学习系统"
之前FastAPI(七十)实战开发《在线课程学习系统》接口开发--留言功能开发分享了留言开发,这次我们分享查看留言
梳理这里的逻辑,这个接口要依赖登录。
梳理后发现,之前在接口设计的时候,有些欠缺,查看留言,是查看单个的留言,查看留言后,对应的留言变成已读状态。那么我们这个都需要传递一个参数,这个参数应该是留言的id。
1.判断用户是否登录
2.判断对应id是否存在,不存在返回对应的错误
3.判断是否是当前用户的留言,或者接受的方是自己
4.返回内容后,同时变成已读
5.如果已读且回复了,要带回复的内容
在之前设计返回状态码的时候,发现状态码有缺失,我们增加下缺失的。
| 状态码 | 含义 |
| 200 | 成功 |
| 100601 | 留言不存在 |
| 100602 | 权限不足 |
首先是pydantic参数模型以及响应模型
class Messages(BaseModel):
id: int
send_user: str
accept_user: str
read: bool
send_time: str
add_time: str
context: str
class MessagePid(Messages):
pid: int
class MessageOne(Messages):
pid: List[MessagePid] = []
然后实现逻辑:message_method.py增加如下
def get_msg_by_id(db, msg_id):
return db.query(Message).filter(Message.id == msg_id, Message.status == 0).first()
def get_pid_message(db, msg_id):
# 获取某条消息被回复的所有消息
return db.query(Message).filter(Message.pid == msg_id, Message.status == 0).all()
def view_msg_method(msg_id: int, user: UsernameRole, db: Session):
"""查看留言(回复的消息和留言在一个表里,结构一样)"""
msg = get_msg_by_id(db, msg_id)
if not msg:
return response(code=100601, message="留言不存在")
db_user = get_by_username(db, user.username)
if msg.accept_user != db_user.id:
return response(code=100602, message="权限不足")
msg.read = True
db.commit()
db.refresh(msg)
all_pid_messages = get_pid_message(db, msg_id) # 查询所有回复的消息
message_one = MessageOne(
id=msg.id,
send_user=get_by_uid(db, msg.send_user).username,
accept_user=get_by_uid(db, msg.accept_user).username,
read=msg.read,
send_time=msg.send_time,
add_time=str(msg.add_time),
context=msg.context
)
# ① 留言没有被回复消息
if not all_pid_messages:
return response(data=message_one.dict())
# ② 留言有被回复的消息,那么需要将回复的消息带回
to_client = []
for _ in all_pid_messages:
msg_pid = MessagePid(
id=msg.id,
send_user=get_by_uid(db, _.send_user).username,
accept_user=get_by_uid(db, _.accept_user).username,
read=_.read,
send_time=_.send_time,
add_time=str(_.add_time),
context=_.context,
pid=_.pid
)
to_client.append(msg_pid)
message_one.pid = to_client
return response(data=message_one.dict())
最后实现接口
@message_router.get("/", summary="查看留言")
async def view_message(
msg_id: int,
user: UsernameRole = Depends(get_current_user),
db: Session = Depends(create_db)
):
return view_msg_method(msg_id, user, db)
测试:

以上则是实现查看留言的接口逻辑
FastAPI在线课程系统留言查看接口
629

被折叠的 条评论
为什么被折叠?



