您的位置:首页 > 游戏 > 手游 > FastAPI(七十六)实战开发《在线课程学习系统》接口开发-- 课程详情

FastAPI(七十六)实战开发《在线课程学习系统》接口开发-- 课程详情

2024/10/5 18:30:47 来源:https://blog.csdn.net/myli_binbin/article/details/140683401  浏览:    关键词:FastAPI(七十六)实战开发《在线课程学习系统》接口开发-- 课程详情

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

这个接口用户可以不登录,因为我们的课程随意浏览

那么我们梳理下这里的逻辑

1.根据课程id判断课程是否存在

2.课程需要返回课程的详情

3.返回课程的评论

首先,我们去设计对应的pydantic类,course_schema.py

class CourseCommentBase(BaseModel):user: strpid: intadd_time: strcontext: strclass CourseComment(CourseCommentBase):id: inttop: intclass CourseDetail(Courses):id: intowner: str  # 此处重写该字段,返回给客户端时展示用户名而非idcomment: List[CourseComment] = []

下面是具体逻辑:course_method.py

def get_course_by_id(db: Session, id: int):"""根据课程id获取课程"""return db.query(Course).filter(Course.id == id, Course.status == False).first()def get_comment_by_course_id(db: Session, course_id: int):return db.query(CourseComment).filter(CourseComment.course == course_id, CourseComment.status == False).all()def get_course_detail(course_id: int, db: Session):"""获取课程详情"""db_course = get_course_by_id(db, course_id)if not db_course:return response(code=101101, message="该课程不存在")try:course_detail = CourseDetail(id=db_course.id,name=db_course.name,icon=db_course.icon,desc=db_course.desc,catalog=db_course.catalog,onsale=db_course.onsale,owner=get_by_uid(db, db_course.owner).username,like_num=db_course.like_num)course_comments = get_comment_by_course_id(db, db_course.id)to_client_comments = []if course_comments:for _ in course_comments:detail_comment = CourseComment(id=_.id,top=_.top,user=get_by_uid(db, _.user).username,pid=_.id,add_time=str(_.add_time),context=_.context)to_client_comments.append(detail_comment)course_detail.comment = to_client_commentsexcept:logger.warning(f"查看课程详情失败")return response(code=101102, message="查看详情失败")return response(data=course_detail.dict())

最后实现我们的接口api,course.py

@course_router.get("/", summary="获取课程详情")
def detail(course_id: int, db: Session = Depends(create_db)):return get_course_detail(course_id, db)

测试:

以上就是我们的课程详情接口,等评论接口开发好后回头再测试一下该接口

版权声明:

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

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