FastAPI(七十六)實戰開發《線上課程學習系統》介面開發-- 課程詳情
阿新 • • 發佈:2022-04-04
這個介面使用者可以不用登入,因為我們的課程可以隨便的人都可以預覽。
那麼我們梳理下這裡面的邏輯
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='')