• FastAPI 学习之路(五十九)封装统一的json返回处理工具


      

           这之前的接口,我们返回的格式都是每个接口异常返回的数据格式都会不一样,我们处理起来没有那么方便,我们可以封装一个统一的json处理。

            那么我们看下如何来实现呢

    from fastapi import status
    from fastapi.responses import JSONResponse, Response  
    from typing import Union
    def resp_200(*, data: Union[list, dict, str]) -> Response:
        return JSONResponse(
            status_code=status.HTTP_200_OK,
            content={
                'code': 200,
                'message': "Success",
                'data': data,
            }
        )  
    def resp_400(*, data: str = None, message: str="BAD REQUEST") -> Response:
        return JSONResponse(
            status_code=status.HTTP_400_BAD_REQUEST,
            content={
                'code': 400,
                'message': message,
                'data': data,
            }
        )

      我们统一的把代码放到common下面的jsontools.py里面,我们在接口返回的时候调用。看下我们处理后的效果。

            我们在创建的用户的时候修改下,用我们的工具统一的处理下

    # 新建用户
    @usersRouter.post("/users/", tags=["users"])
    def create_user(user: UserCreate, db: Session = Depends(get_db)):
        """
            - **email**: 用户的邮箱
            - **password**: 用户密码
            """
        db_crest = get_user_emai(db, user.email)
        user.password = get_password_hash(user.password)
        if not db_crest:
            user=db_create_user(db=db, user=user)
            return resp_200(data={'user':user.email})
        return  resp_200(data={'detail':"账号不能重复"})

     我们看下postman的返回

      我们看创建重复的返回

      但是我们看着返回的code都是固定的,那么我们是否可以升级改造下。

    def reponse(*, code=200,data: Union[list, dict, str],message="Success") -> Response:
        return JSONResponse(
            status_code=status.HTTP_200_OK,
            content={
                'code': code,
                'message': message,
                'data': data,
            }
        )

      新改造后,我们的返回,可以自定义code ,message和data。那么我们去改造下我们创建的用户的接口

    # 新建用户
    @usersRouter.post("/users/", tags=["users"])
    def create_user(user: UserCreate, db: Session = Depends(get_db)):
        """
            - **email**: 用户的邮箱
            - **password**: 用户密码
            """
        db_crest = get_user_emai(db, user.email)
        user.password = get_password_hash(user.password)
        if not db_crest:
            user=db_create_user(db=db, user=user)
            return reponse(code=0,data={'user':user.email},message="success")
        return  reponse(data={'msg':"账号不能重复"},code=1,message="error")
        

      我们看下修改后的用户返回

     

      这样我们就完成了统一的接口响应的处理,后续我们可以在所有的接口中使用。

    代码存储https://gitee.com/liwanlei/fastapistuday

    文章首发在公众号,欢迎关注。

  • 相关阅读:
    MySQL数据库的基本数据类型
    Mybatis学习记录(八)----Mybatis整合Spring
    Mybatis学习记录(七)----Mybatis查询缓存
    Mybatis学习记录(七)----Mybatis延迟加载
    Mybatis学习记录(六)----Mybatis的高级映射
    Mybatis学习记录(五)----Mybatis的动态SQL
    Mybatis学习记录(四)----resultMap的使用
    Mybatis学习记录(三)----理解SqlMapConfig.xml文件
    Vue生命周期
    vue简单路由(二)
  • 原文地址:https://www.cnblogs.com/leiziv5/p/15416953.html
Copyright © 2020-2023  润新知