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

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

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

相关推荐
余槐i4 天前
拆解 Agent 核心原理|从零动手实现简易 AI 智能体(三)
人工智能·python·fastapi·ai agent
醇氧4 天前
Git 合并冲突与`__pycache__` 的恩怨情仇
python·numpy·fastapi
甜到心里的蛋糕4 天前
如何用企业微信实现让微信收到通知实时通知
服务器·python·微信小程序·fastapi
basketball6165 天前
Python FastAPI 介绍以及常用方法
python·fastapi·vllm·ai infra
troy1286 天前
Codex 安全盲区:代码漏洞生成实测
windows·python·ci/cd·pycharm·django·github·fastapi
打工仔折腾 AI7 天前
FastAPI 从本机到生产服务器:Nginx+Gunicorn+Uvicorn 完整部署实录
人工智能·后端·python·nginx·fastapi·gunicorn
西安栈上月明软件科技8 天前
从 Linux 0.01 到 AI 开源:星图邻的开源实践
人工智能·自然语言处理·架构·开源·fastapi
troy1288 天前
Python 基础语法(九):Django/Flask/FastAPI 三大 Web 框架详细对比解析
python·jupyter·django·flask·github·fastapi
刚子编程9 天前
Ubuntu 22.04 Docker 从零部署全栈项目实录:Next.js + FastAPI + PostgreSQL 一次跑通
fastapi·nextjs·docker部署·全栈开发·ubuntu22.04
CSharp精选营10 天前
Ubuntu 22.04 Docker 从零部署全栈项目实录:Next.js + FastAPI + PostgreSQL 一次跑通
fastapi·nextjs·docker部署·全栈开发·ubuntu22.04