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

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

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

相关推荐
俊俊谢16 小时前
[python]FastAPI + 自建SSE 踩坑全记录
开发语言·python·fastapi
li星野17 小时前
从零搭建 DeepSeek LLM API 服务:FastAPI + LlamaIndex 实践
fastapi
勇往直前plus1 天前
FastAPI + SQLAlchemy PythonWeb体系梳理
fastapi·python3.11
放下华子我只抽RuiKe52 天前
FastAPI 全栈后端(四):认证与授权
开发语言·前端·javascript·python·深度学习·react.js·fastapi
放下华子我只抽RuiKe52 天前
FastAPI 全栈后端(六):中间件与依赖注入
ai·中间件·fastapi·ai编程·qwen·ai大模型·openclaw
li星野2 天前
Refresh Token 实战:让用户“无感”续期,告别重复登录
fastapi
放下华子我只抽RuiKe52 天前
FastAPI 全栈后端(五):后台任务与消息队列
前端·javascript·react.js·ai·前端框架·fastapi·ai编程
li星野3 天前
从零构建安全文件上传系统:FastAPI + JWT + 密码哈希 + Streamlit 前端 + SQLite
安全·哈希算法·fastapi
郭庆汝4 天前
FastAPI使用笔记
笔记·fastapi
放下华子我只抽RuiKe54 天前
FastAPI 全栈后端(二):路由与数据模型
前端·人工智能·react.js·前端框架·html·fastapi