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

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

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

相关推荐
Anesthesia丶2 天前
Vue3 + naive-ui + fastapi使用心得
vue.js·ui·fastapi
weixin_307779132 天前
使用FastAPI微服务在AWS EKS中构建上下文增强型AI问答系统
人工智能·python·云计算·fastapi·aws
掘金-我是哪吒2 天前
分布式微服务系统架构第130集:Python工程化FastAPI,运维Nginx-keepalived+Nginx实现高可用集群
运维·分布式·微服务·系统架构·fastapi
LingRannn2 天前
JWT的介绍与在Fastapi框架中的应用
fastapi
Python私教3 天前
使用FastAPI和React以及MongoDB构建全栈Web应用05 FastAPI快速入门
前端·react.js·fastapi
Python私教3 天前
全栈开发实战:FastAPI + React + MongoDB 构建现代Web应用
前端·react.js·fastapi
weixin_307779134 天前
使用FastAPI和Apache Flink构建跨环境数据管道
redis·python·云计算·fastapi·aws
真智AI7 天前
构建安全的机器学习推理API:基于FastAPI的用户认证与管理实战
安全·机器学习·fastapi
Data 实验室10 天前
爬虫管理平台-最新版本发布
开发语言·爬虫·python·fastapi
eihh2333310 天前
模型部署与提供服务
fastapi·llamafactory