源码见:"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)
测试:
以上就是我们的课程详情接口,等评论接口开发好后回头再测试一下该接口