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)

测试

相关推荐
爱敲代码的TOM19 小时前
PythonWeb基础-FastAPI使用
python·fastapi
simon_skywalker1 天前
FastAPI实战笔记(二) 数据处理
fastapi
创新技术阁2 天前
CryptoAiAdmin项目数据库表自动创建和初始化
后端·python·fastapi
懒人村杂货铺2 天前
前端步入全栈第一步
前端·docker·fastapi
simon_skywalker2 天前
FastAPI实战笔记(一) 基本介绍与简单操作
fastapi
wang6021252182 天前
阿里云存储的一些简要概述
数据库·阿里云·fastapi
山沐与山3 天前
【设计模式】Python工厂模式与依赖注入:FastAPI的Depends到底在干嘛
python·设计模式·fastapi
祁思妙想3 天前
修改python后端项目名称:pycharm中fastapi框架的项目
ide·pycharm·fastapi
钱彬 (Qian Bin)3 天前
项目实践13—全球证件智能识别系统(内网离线部署大模型并调用)
数据库·postgresql·fastapi·ubuntu24.04·离线部署·qwen3大模型
安冬的码畜日常4 天前
【玩转 Postman 接口测试与开发2_020】(完结篇)DIY 实战:随书示例 API 项目本地部署保姆级搭建教程(含完整调试过程)
python·测试工具·django·接口测试·postman·fastapi·api项目