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下面的json_tools.py里面,我们在接口返回的时候调用

from common.json_tools import resp_200

def create_user_method(db: Session, user: UserModel):
    db_user = db.query(User).filter(User.email == user.email).first()
    if db_user:
        return resp_200(data={"detail": "this user already exists"})
    from routers.users import get_password_hash
    hashed_password = get_password_hash(user.password)
    init_user = User(email=user.email, hashed_password=hashed_password)
    db.add(init_user)
    db.commit()
    db.refresh(init_user)
    return resp_200(data={"user": init_user.email})

我们看下处理后的效果

我们看创建重复的返回

但是我们发现code返回的都是固定的,那么我们是否可以改造下:

def response(*, 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。接下来我们再次改造下我们的新建用户的接口

from common.json_tools import response

def create_user_method(db: Session, user: UserModel):
    db_user = db.query(User).filter(User.email == user.email).first()
    if db_user:
        return response(code=1, message="error", data="this user already exists")
    from routers.users import get_password_hash
    hashed_password = get_password_hash(user.password)
    init_user = User(email=user.email, hashed_password=hashed_password)
    db.add(init_user)
    db.commit()
    db.refresh(init_user)
    return resp_200(data={"user": init_user.email})

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

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

相关推荐
用户673559885613 小时前
数据驱动,实时监控显威力 —— 淘宝商品详情API助力商家精准营销
后端·api·fastapi
_.Switch8 小时前
Python Web 开发中的性能优化策略(一)
开发语言·前端·python·性能优化·django·flask·fastapi
黑金IT5 天前
WebSocket vs. Server-Sent Events:选择最适合你的实时数据流技术
网络·python·websocket·网络协议·fastapi
黑金IT5 天前
FastAPI 应用安全加固:HTTPSRedirectMiddleware 中间件全解析
安全·中间件·fastapi
写bug如流水6 天前
【FastAPI】实现服务器向客户端发送SSE(Server-Sent Events)广播
服务器·python·fastapi
黑金IT6 天前
从单体到微服务:FastAPI ‘挂载’子应用程序的转变
微服务·架构·fastapi
不良人龍木木7 天前
sqlalchemy FastAPI 前端实现数据库增删改查
前端·数据库·fastapi
写bug如流水7 天前
【FastAPI】离线使用Swagger UI 或 国内网络如何快速加载Swagger UI
ui·fastapi·命令模式
布响哒公9 天前
用python fastapi写一个http接口,使ros2机器人开始slam toolbox建图
python·机器人·fastapi
_.Switch11 天前
Python Web 框架篇:Flask、Django、FastAPI介绍及其核心技术
开发语言·前端·后端·python·django·flask·fastapi