FastAPI(七十七)实战开发《在线课程学习系统》接口开发-- 课程编辑和查看评论

源码见:"fastapi_study_road-learning_system_online_courses: fastapi框架实战之--在线课程学习系统"

课程编辑

先来看下课程编辑

1.判断是否登录

2.判断课程是否存在

3.是否有权限(只有自己可以修改自己的课程)

4.名称是否重复

首先,新增一个参数pydantic

复制代码
class CourseEdit(Courses):
    id: int

其次,增加主要逻辑

复制代码
def edit_course(course: CourseEdit, db: Session, user: UsernameRole):
    """编辑课程"""
    db_course = get_course_by_id(db, course.id)
    if not db_course:
        return response(code=101201, message="课程不存在")
    db_user = get_by_username(db, user.username)
    if db_user.id != course.owner:
        return response(code=101202, message="权限不足")
    exists = get_course_by_name(db, course.name)
    if exists:
        return response(code=101203, message="该课程名称已存在")
    try:
        # 这里只是修改课程的属性,上架下架不能在这改
        db_course.catalog = course.catalog
        db_course.desc = course.desc
        db_course.icon = course.icon
        db_course.name = course.name
        db.commit()
        db.refresh(db_course)
    except:
        logger.warning(f"method edit_course error:{traceback.format_exc()}")
        return response(code=101204, message="修改失败")
    return response()

最后,实现接口api

复制代码
@course_router.put("/", summary="编辑课程")
def edit(
        course: CourseEdit,
        db: Session = Depends(create_db),
        user: UsernameRole = Depends(get_current_user)):
    return edit_course(course, db, user)

测试:

查看评论

接下来看下查看评论

1.判断课程是否存在

2.存在返回所有评论

主要逻辑

复制代码
def get_course_comment(course_id: int, db: Session):
    """获取课程评论"""
    db_course = get_course_by_id(db, course_id)
    if not db_course:
        return response(code=101301, message="课程不存在")
    comments = get_comment_by_course_id(db, course_id)
    to_client = []
    if comments:
        for _ in comments:
            detail_comment = CourseCommentOut(
                id=_.id,
                top=_.top,
                user=get_by_uid(db, _.user).username,
                pid=_.pid,
                add_time=str(_.add_time),
                context=_.context
            )
            to_client.append(detail_comment.dict())
    return response(data=to_client)

因为course_schema.py中的CourseComment和models中的重名了,所以做了修改

复制代码
class CourseCommentOut(CourseCommentBase):
    id: int
    top: int


class CourseDetail(Courses):
    id: int
    owner: str  # 此处重写该字段,返回给客户端时展示用户名而非id
    comment: List[CourseCommentOut] = []

实现api

复制代码
@course_router.get("/course_comment", summary="查看课程评论")
def course_comment(course_id: int,
        db: Session = Depends(create_db)):
    return get_course_comment(course_id, db)

测试

这样我们的课程编辑和查看评论接口就完成了

相关推荐
强化试剂瓶11 小时前
Silane-PEG8-DBCO,硅烷-聚乙二醇8-二苯并环辛炔技术应用全解析
python·flask·numpy·pyqt·fastapi
曲幽14 小时前
FastAPI日志实战:从踩坑到优雅配置,让你的应用会“说话”
python·logging·fastapi·web·error·log·info
布局呆星1 天前
FastAPI:高性能Python Web框架
fastapi
曲幽2 天前
FastAPI异步多线程:从踩坑到精通,解锁高性能API的正确姿势
python·flask·fastapi·web·thread·async·httpx·asyncio
玄同7652 天前
深入理解 SQLAlchemy 的 relationship:让 ORM 关联像 Python 对象一样简单
人工智能·python·sql·conda·fastapi·pip·sqlalchemy
翱翔的苍鹰2 天前
完整的“RNN + jieba 中文情感分析”项目之一:添加 API 接口(FastAPI) 和 支持 批量分析
人工智能·rnn·fastapi
曲幽3 天前
FastAPI异常处理全解析:别让你的API在用户面前“裸奔”
python·websocket·api·fastapi·web·exception·error·httexception
Loo国昌3 天前
深入理解 FastAPI:Python高性能API框架的完整指南
开发语言·人工智能·后端·python·langchain·fastapi
摸鱼仙人~3 天前
从 Gunicorn 到 FastAPI:Python Web 生产环境架构演进与实战指南
python·fastapi·gunicorn
这儿有一堆花3 天前
实战:FastAPI与WebSocket的高并发足球数据API开发指南
websocket·网络协议·fastapi