欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > FastAPI(七十八)实战开发《在线课程学习系统》接口开发-- 评论

FastAPI(七十八)实战开发《在线课程学习系统》接口开发-- 评论

2025/2/25 1:08:40 来源:https://blog.csdn.net/myli_binbin/article/details/140690247  浏览:    关键词:FastAPI(七十八)实战开发《在线课程学习系统》接口开发-- 评论

源码见:"fastapi_study_road-learning_system_online_courses: fastapi框架实战之--在线课程学习系统"

梳理下思路

1.判断是否登录

2.课程是否存在

3.如果是回复,查看回复是否存在

4.是否有权限

5.发起评论

首先新增pydantic模型

class CourseCommentModel(BaseModel):"""发起评论参数"""id: intcomment: str = Field(min_length=1)pid: Optional[int] = None

其次实现主要逻辑


def to_comment_method(comment: CourseCommentModel, user: UsernameRole, db: Session):"""发起评论"""db_user = get_by_username(db, user.username)db_course = get_course_by_id(db, comment.id)if not db_course:return response(code=101401, message="课程不存在")if db_course.owner == db_user.id and comment.pid is None:return response(code=101404, message="自己不能评论自己的课程")if comment.pid:pid_course = get_course_by_id(db, comment.pid)if not pid_course:return response(code=101405, message="回复的评论不存在")return create_comment(db, comment, db_user.id)return create_comment(db, comment, db_user.id)def create_comment(db: Session, comment: CourseCommentModel, user: int):"""保存评论"""# 前提:自己不能给自己的课程发起评论,但是发起评论后可以给自己的评论回复try:to_db_comment = CourseComment(course=comment.id,user=user,pid=comment.pid,context=comment.comment)to_db_comment.user = userdb.add(to_db_comment)db.commit()db.refresh(to_db_comment)except:logger.warning(f"method create_comment error: {traceback.format_exc()}")return response(code=101402, message="评论失败")return response()

最后,实现接口api

@course_router.post("/course_comment", summary="发起评论")
def to_comment(comment: CourseCommentModel, user: UsernameRole = Depends(get_current_user),db: Session = Depends(create_db)):return to_comment_method(comment, user, db)

测试

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词