FastAPI(七十八)实战开发《在线课程学习系统》接口开发-- 评论

源码见:"fastapi_study_road-learning_system_online_courses: fastapi框架实战之--在线课程学习系统"

梳理下思路

1.判断是否登录

2.课程是否存在

3.如果是回复,查看回复是否存在

4.是否有权限

5.发起评论

首先新增pydantic模型

class CourseCommentModel(BaseModel):
    """发起评论参数"""
    id: int
    comment: str = Field(min_length=1)
    pid: Optional[int] = None

其次实现主要逻辑

def to_comment_method(comment: CourseCommentModel, user: UsernameRole, db: Session):
    """发起评论"""
    db_user = get_by_username(db, user.username)
    db_course = get_course_by_id(db, comment.id)
    if not db_course:
        return response(code=101401, message="课程不存在")
    if db_course.owner == db_user.id and comment.pid is None:
        return response(code=101404, message="自己不能评论自己的课程")
    if comment.pid:
        pid_course = get_course_by_id(db, comment.pid)
        if not pid_course:
            return response(code=101405, message="回复的评论不存在")
        return create_comment(db, comment, db_user.id)
    return create_comment(db, comment, db_user.id)


def create_comment(db: Session, comment: CourseCommentModel, user: int):
    """保存评论"""
    # 前提:自己不能给自己的课程发起评论,但是发起评论后可以给自己的评论回复
    try:
        to_db_comment = CourseComment(
            course=comment.id,
            user=user,
            pid=comment.pid,
            context=comment.comment
            )
        to_db_comment.user = user
        db.add(to_db_comment)
        db.commit()
        db.refresh(to_db_comment)
    except:
        logger.warning(f"method create_comment error: {traceback.format_exc()}")
        return response(code=101402, message="评论失败")
    return response()

最后,实现接口api

@course_router.post("/course_comment", summary="发起评论")
def to_comment(comment: CourseCommentModel, user: UsernameRole = Depends(get_current_user),
               db: Session = Depends(create_db)):
    return to_comment_method(comment, user, db)

测试

相关推荐
_.Switch9 天前
Python Web开发:使用FastAPI构建视频流媒体平台
开发语言·前端·python·微服务·架构·fastapi·媒体
ghostwritten10 天前
Python FastAPI 实战应用指南
开发语言·python·fastapi
殷丿grd_志鹏13 天前
SpringCloud+Vue+Python人工智能(fastAPI,机器学习,深度学习)前后端架构各功能实现思路——主目录(持续更新)
vue.js·人工智能·python·spring cloud·fastapi
_.Switch13 天前
FastAPI 应用的容器化与 Docker 部署:提升性能与可扩展性
数据库·python·网络协议·docker·容器·eureka·fastapi
m0_7482567815 天前
开源模型应用落地-FastAPI-助力模型交互-进阶篇-中间件(四)
开源·交互·fastapi
_.Switch15 天前
高级Python Web开发:FastAPI前后端通信与跨域资源共享(CORS)实现详解
开发语言·前端·数据库·后端·python·中间件·fastapi
_.Switch16 天前
高效构建与部署Python Web应用:FastAPI的测试与持续集成
前端·网络·数据库·python·ci/cd·fastapi
_.Switch21 天前
FastAPI 的依赖注入与生命周期管理深度解析
开发语言·前端·python·中间件·性能优化·fastapi
namelijink24 天前
docker-compose部署下Fastapi中使用sqlalchemy和Alembic
adb·docker·fastapi
测开小林25 天前
Fastapi + vue3 自动化测试平台(2)--日志中间件
自动化测试·中间件·fastapi·测试工具开发