FastAPI(七十二)实战开发《在线课程学习系统》接口开发-- 留言列表开发
之前我们分享了FastAPI(七十一)实战开发《在线课程学习系统》接口开发-- 查看留言,这次我们分享留言列表开发。
列表获取,也需要登录,根据登录用户来获取对应的留言。逻辑梳理如下。
1.判断用户是否登录 2.根据登录用户查询留言列表 3.留言列表中要根据是留言回复,进行列表重组
我们根据逻辑去梳理下对应的crud
def get_message_list(db: Session, userid: int): return db.query(Message).filter(or_(Message.senduser.id == userid, Message.acceptusers.id == userid,Message.status==0)).all()
我们根据逻辑去开发对应的代码。
@usersRouter.get(path="/messagelist") async def messagelist(user: UsernameRole = Depends(get_cure_user), db: Session = Depends(get_db)): users = get_user_username(db, user.username) messagelist = get_message_list(db=db, userid=users.id) message_list = [] mainmessage = [] if len(messagelist) > 0: for item in messagelist: if item.pid == "": messageone = MessageOne(id=item.id, senduser=get_user(db,item.senduser).username, acceptusers=get_user(db,item.acceptusers).username, read=item.read, sendtime=item.sendtime, addtime=str(item.addtime), context=item.context) mainmessage.append(messageone.id) all_pid = get_pid_message(db, item.id) if len(all_pid) > 0: allpidlist = [] for items in all_pid: message = MessagePid(id=item.id, senduser=get_user(db,items.senduser).username, acceptusers=get_user(db,items.acceptusers).username, read=items.read, sendtime=items.sendtime, addtime=str(items.addtime), context=items.context, pid=items.pid) allpidlist.append(message) messageone.pid = allpidlist message_list.append(messageone) else: if item.pid not in mainmessage: message = get_message(db, item.pid) if message: all_pid = get_pid_message(db, message.id) messageone = MessageOne(id=message.id, senduser=get_user(db,message.senduser).username, acceptusers=get_user(db,message.acceptusers).username, read=message.read, sendtime=message.sendtime, addtime=str(message.addtime), context=message.context) if len(all_pid) > 0: allpidlist = [] for item in all_pid: messagepid = MessagePid(id=message.id, senduser=get_user(db,item.senduser).username, acceptusers=get_user(db,item.acceptusers).username, read=item.read, sendtime=item.sendtime, addtime=str(item.addtime), context=item.context, pid=item.pid) allpidlist.append(messagepid) messageone.pid = allpidlist message_list.append(messageone) return reponse(code=200, message='成功', data=jsonable_encoder(message_list))