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 小时前
分布式微服务系统架构第144集:FastAPI全栈开发教育系统
分布式·微服务·架构·系统架构·fastapi
jingyucsdn6 天前
AsyncIOScheduler与BackgroundScheduler的线程模型对比
fastapi
jingyucsdn7 天前
FastAPI集成APsecheduler的BackgroundScheduler+mongodb(精简)
fastapi
几道之旅7 天前
前端antd,后端fastapi,解决文件上传
前端·fastapi
Hello_WOAIAI8 天前
python中使用高并发分布式队列库celery的那些坑
python·fastapi
ZHOU_WUYI10 天前
FastAPI在 Nginx 和 Docker 环境中的部署
nginx·docker·fastapi
王学政210 天前
FastAPI 中间件
fastapi
小迅先生13 天前
AI开发 | Web API框架选型-FastAPI
开发语言·python·fastapi
老大白菜15 天前
双均线量化交易策略指南
python·fastapi
Msshu12315 天前
消费类,小家电产品如何做Type-C PD快充快速充电
python·单片机·嵌入式硬件·物联网·beautifulsoup·fastapi·tornado