源码见:"fastapi_study_road-learning_system_online_courses: fastapi框架实战之--在线课程学习系统"
推荐课程列表
逻辑很简单
点赞数 > 500
那么符合要求的课程是:
def get_like_course(db: Session):"""获取推荐课程(点赞数超500的课程)"""return db.query(Course).filter(Course.like_num > 500, Course.status == False).all()def like_method(db: Session):"""返回推荐课程逻辑"""try:all_likes = get_like_course(db)to_client = []if all_likes:for _ in all_likes:course_detail = CourseDetail(id=_.id,name=_.name,icon=_.icon,desc=_.desc,catalog=_.catalog,onsale=_.onsale,owner=get_by_uid(db, _.owner).username,like_num=_.like_num)to_client.append(course_detail.dict())except:logger.warning(f"method like_method error: {traceback.format_exc()}")return response(code=101801, message="查询错误")return response(data=to_client)
接口api
@course_router.get("/like", summary="获取推荐课程")
def like(db: Session = Depends(create_db)):return like_method(db)
测试:
我们推荐课程用的点赞数大于500的,那么我们看下如何点赞
点赞课程
1.是否登录
2.是否是学生
3.是否点赞过
4.点赞成功,redis记录点赞的人
对应的状态码更新如下
状态码 | 含义 |
200 | 成功 |
102002 | 已经点赞,不能重复点赞 |
102001 | 课程不存在 |
逻辑实现如下:
async def add_like_method(request: Request, course_id: int, user: UsernameRole, db: Session):"""点赞课程"""db_course = get_course_by_id(db, course_id)if not db_course:return response(code=102001, message="课程不存在")if user.role != "学生":return response(code=102004, message="只有学生才可以点赞")like_key = str(db_course.id) + "_like"redis_result = await request.app.state.redis.hgetall(like_key, encoding="utf-8")username = user.usernameif username in redis_result.keys():return response(code=102002, message="不能重复点赞")try:await request.app.state.redis.hmset_dict(like_key, {username: 1})db_course.like_num += 1db.commit()db.refresh(db_course)except:logger.warning(f"method add_like_method error: {traceback.format_exc()}")return response(code=102003, message="点赞失败")return response()
接口api
@course_router.post("/like", summary="点赞课程")
async def add_like(request: Request, course_id: int, user: UsernameRole = Depends(get_current_user), db: Session = Depends(create_db)):return await add_like_method(request, course_id, user, db)
测试
以上测试推荐课程列表和点赞课程的接口逻辑