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})

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

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

相关推荐
曲幽4 小时前
FastAPI子应用挂载:别再让root_path坑你一夜
python·nginx·fastapi·web·mount·admin·404·docs·root_path
Ares-Wang6 小时前
Python》》FastAPI 异步框架 接口 pymysql【同步】 aiomysql【异步】
开发语言·python·fastapi
Thomas.Sir9 小时前
第十四章:基于 FastAPI+Vue3 的智能聊天系统全栈开发实战
vue·状态模式·fastapi·智能
在屏幕前出油2 天前
06. FastAPI——中间件
后端·python·中间件·pycharm·fastapi
github_czy2 天前
Python 函数式编程利器:Partial 与 ParamSpec 技术解析
python·fastapi
github_czy2 天前
FastAPI 流式响应核心原理解析(含前端断开感知)
前端·fastapi
tryCbest2 天前
Python之FastAPI 高级特性总结与完整项目实战
开发语言·python·fastapi
Ares-Wang2 天前
flask 》》pymysql VS FastAPI aiomysql
数据库·flask·fastapi
小陈工3 天前
2026年3月26日技术资讯洞察:WebAssembly崛起、AI代码质量危机与开源安全新挑战
人工智能·python·安全·架构·开源·fastapi·wasm
曲幽3 天前
FastAPI项目半夜报警吵醒你?聊聊告警这事儿怎么搞!
python·logging·fastapi·web·monitoring·webserver·health·uptimerobot