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)

测试

相关推荐
onelafite1 天前
小红书笔记评论一键获取,实时查看作品数据
api·fastapi
shao9185162 天前
Gradio全解11——Streaming:流式传输的视频应用(2)——Twilio:网络服务提供商
fastapi·handler·stun·turn·ice·twillo
枫叶V2 天前
用 FastAPI 实现大文件分片上传与断点续传(含可运行示例与客户端脚本,仅供参考)
python·fastapi
蓝倾5 天前
利用API接口合规获取淘宝店铺所有商品实战案例(2025年最新版)
api·fastapi
肥肠可耐的西西公主6 天前
后端(fastAPI)学习笔记(CLASS 1):扩展基础
笔记·学习·fastapi
红鼻子时代7 天前
Day5-中间件与请求处理
中间件·fastapi·后端开发
蓝倾8 天前
京东商品属性API数据解析:颜色、尺寸与材质
api·fastapi
CodeDevMaster9 天前
使用Transformers、ChatGLM3项目、创建FastAPI应用等方式部署调用ChatGLM3-6B模型
llm·fastapi·chatglm (智谱)
我就是全世界11 天前
【2025终极对决】Python三大后端框架Django vs FastAPI vs Robyn,你的选择将决定项目生死?
python·django·fastapi
威风的虫13 天前
FastAPI 核心实战:精通路径参数、查询参数与数据交互
python·交互·fastapi