源码见:"fastapi_study_road-learning_system_online_courses: fastapi框架实战之--在线课程学习系统"
课程上架/下架
1、是否登录
2、角色权限
3、课程是否存在
4、是否是自己的课程
4、课程如果是上架状态,则下架,反之,则上架
具体逻辑实现
def onsale_method(course_id: int, user: UsernameRole, db: Session):"""上架/下架 课程"""if user.role == "学生":return response(code=102101, message="权限不足")db_course = get_course_by_id(db, course_id)if not db_course:return response(code=102102, message="课程不存在")db_user = get_by_username(db, user.username)if db_user.id != db_course.owner:return response(code=102103, message="自己只能上架或下架自己的课程")try:if db_course.onsale: # 下架db_course.onsale = Falseelse: # 上架db_course.onsale = Truedb.commit()db.refresh(db_course)except:logger.warning(f"method onsale_method error: {traceback.format_exc()}")if db_course.onsale:msg = "下架失败"else:msg = "上架失败"return response(code=102104, message=msg)return response()
接口api
@course_router.post("/onsale", summary="上架/下架 课程")
def onsale(course_id: int, user: UsernameRole = Depends(get_current_user), db: Session = Depends(create_db)):return onsale_method(course_id, user, db)
测试