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='')

  

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章