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)

测试

相关推荐
写代码的【黑咖啡】9 小时前
Python Web 开发新宠:FastAPI 全面指南
前端·python·fastapi
曲幽10 小时前
FastAPI实战:WebSocket vs Socket.IO,这回真给我整明白了!
python·websocket·nginx·socket·fastapi·web·async·socketio
I'm Jie10 小时前
Swagger UI 本地化部署,解决 FastAPI Swagger UI 依赖外部 CDN 加载失败问题
python·ui·fastapi·swagger·swagger ui
七夜zippoe14 小时前
OpenClaw 会话管理:单聊、群聊、多模型
大数据·人工智能·fastapi·token·openclaw
别催小唐敲代码2 天前
FastAPI 从零开始完整学习教程
学习·fastapi
05大叔2 天前
FastAPI框架 路径,查询,请求体参数,JSON,文本,HTML响应类型,异常
fastapi
小陈工2 天前
FastAPI性能优化实战:从每秒100请求到1000的踩坑记录
python·性能优化·django·flask·numpy·pandas·fastapi
带娃的IT创业者2 天前
WeClaw 日志分析实战:如何从海量日志中快速定位根因?
运维·python·websocket·jenkins·fastapi·架构设计·实时通信
天下无贼!2 天前
【Python】2026版——FastAPI 框架快速搭建后端服务
开发语言·前端·后端·python·aigc·fastapi
带娃的IT创业者3 天前
Weclaw 混合通讯架构实战:HTTP+SSE+WebSocket的三元融合如何支撑起整个 AI 助手的实时对话?
websocket·http·fastapi·sse·流式响应·实时通讯·混合架构