IT评测·应用市场-qidao123.com技术社区

标题: FastAPI(七十八)实战开发《在线课程学习系统》接口开发-- 品评 [打印本页]

作者: 王國慶    时间: 2024-7-30 18:09
标题: FastAPI(七十八)实战开发《在线课程学习系统》接口开发-- 品评
源码见:"fastapi_study_road-learning_system_online_courses: fastapi框架实战之--在线课程学习系统"
梳理下思路
   1.判断是否登录
  2.课程是否存在
  3.如果是复兴,查看复兴是否存在
  4.是否有权限
  5.发起品评
  首先新增pydantic模型
  1. class CourseCommentModel(BaseModel):
  2.     """发起评论参数"""
  3.     id: int
  4.     comment: str = Field(min_length=1)
  5.     pid: Optional[int] = None
复制代码
其次实现重要逻辑
  1. def to_comment_method(comment: CourseCommentModel, user: UsernameRole, db: Session):
  2.     """发起评论"""
  3.     db_user = get_by_username(db, user.username)
  4.     db_course = get_course_by_id(db, comment.id)
  5.     if not db_course:
  6.         return response(code=101401, message="课程不存在")
  7.     if db_course.owner == db_user.id and comment.pid is None:
  8.         return response(code=101404, message="自己不能评论自己的课程")
  9.     if comment.pid:
  10.         pid_course = get_course_by_id(db, comment.pid)
  11.         if not pid_course:
  12.             return response(code=101405, message="回复的评论不存在")
  13.         return create_comment(db, comment, db_user.id)
  14.     return create_comment(db, comment, db_user.id)
  15. def create_comment(db: Session, comment: CourseCommentModel, user: int):
  16.     """保存评论"""
  17.     # 前提:自己不能给自己的课程发起评论,但是发起评论后可以给自己的评论回复
  18.     try:
  19.         to_db_comment = CourseComment(
  20.             course=comment.id,
  21.             user=user,
  22.             pid=comment.pid,
  23.             context=comment.comment
  24.             )
  25.         to_db_comment.user = user
  26.         db.add(to_db_comment)
  27.         db.commit()
  28.         db.refresh(to_db_comment)
  29.     except:
  30.         logger.warning(f"method create_comment error: {traceback.format_exc()}")
  31.         return response(code=101402, message="评论失败")
  32.     return response()
复制代码
最后,实现接口api
  1. @course_router.post("/course_comment", summary="发起评论")
  2. def to_comment(comment: CourseCommentModel, user: UsernameRole = Depends(get_current_user),
  3.                db: Session = Depends(create_db)):
  4.     return to_comment_method(comment, user, db)
复制代码
测试



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com技术社区 (https://dis.qidao123.com/) Powered by Discuz! X3.4