FastAPI(七十六)实战开发《在线课程学习系统》接口开发-- 课程详情
这个接口用户可以不用登录,因为我们的课程可以随便的人都可以预览。
那么我们梳理下这里面的逻辑
1.根据id判断课程是否存在
2.课程需要返回课程的详情
3.返回课程的评论
我们去设计对应的课程详情的pydantic 类。
class CoursesCommentBase(BaseModel): users: str pid: int addtime: str context: str class Coursescomment(CoursesCommentBase): id: int top: int class CousesDetail(Courses): id:int commonet: List[Coursescomment] = []
我们看对应的crud
def db_get_course_id(db: Session, id: int): return db.query(Course).filter(Course.id == id, Course.status == False).first() def db_get_coursecomment_id(db: Session, id: int): return db.query(Commentcourse).filter(Commentcourse.course == id, Commentcourse.status == False).all()
对应的业务逻辑代码
@courseRouter.get(path='/detail/{id}')
async def detail(id: int,
db: Session = Depends(get_db)):
course = db_get_course_id(db, id)
if course:
coursedetail = CousesDetail(id=course.id,
name=course.name,
icon=course.icon, desc=course.desc, catalog=course.catalog,
onsale=course.onsale, owner=get_user(db, course.owner).username,
likenum=course.likenum)
allcomments = db_get_coursecomment_id(db, course.id)
all_comments_list = []
if len(allcomments) > 0:
for item in allcomments:
detailcomment = Coursescomment(id=item.id,
top=item.top,
users=get_user(db, item.users).username,
pid=item.id, addtime=str(item.addtime),
context=item.context)
all_comments_list.append(detailcomment)
coursedetail.commonet = all_comments_list
return reponse(code=200, message='成功', data=jsonable_encoder(coursedetail))
return reponse(code=200, message="成功", data='')

浙公网安备 33010602011771号