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

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

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

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

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

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

3.返回课程的评论

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

class CourseCommentBase(BaseModel):
    user: str
    pid: int
    add_time: str
    context: str


class CourseComment(CourseCommentBase):
    id: int
    top: int


class CourseDetail(Courses):
    id: int
    owner: str  # 此处重写该字段,返回给客户端时展示用户名而非id
    comment: 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_comments
    except:
        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)

测试:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值