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)

测试

相关推荐
祁思妙想12 小时前
Python中的FastAPI框架的设计特点和性能优势
开发语言·python·fastapi
Swizard17 小时前
告别“意大利面条”:FastAPI 生产级架构的最佳实践指南
python·fastapi
曲幽1 天前
FastAPI入门:从简介到实战,对比Flask帮你选对框架
python·flask·fastapi·web·route·uv·uvicorn·docs
龙腾AI白云1 天前
基于Tensorflow库的RNN模型预测实战Tensorflow库简介循环神经网络简介
人工智能·fastapi
写文章的大米2 天前
10分钟用Python搭个接口,还能自动生成文档?
python·fastapi
weixin_462446233 天前
【实践原创】使用 FastAPI 实现 Coze 流式聊天 SSE 接口
fastapi·扣子mcp
吴佳浩 Alben3 天前
Python入门指南(五) - 为什么选择 FastAPI?
开发语言·python·fastapi
kkoral3 天前
基于MS-Swift 为 Qwen3-0.6B-Base 模型搭建可直接调用的 API 服务
python·conda·fastapi·swift
AIOps打工人3 天前
Grafana Query MCP:基于FastAPI的Grafana查询转换与分页服务
运维·数据库·python·ai·grafana·fastapi·devops
吴佳浩3 天前
Python入门指南(五) - 为什么选择 FastAPI?
后端·python·fastapi