如何使用ORJSONResponse增强FastAPI应用性能:转换任意类型为JSON

news/2024/9/18 22:39:42 标签: fastapi, json, python

在FastAPI中,ORJSONResponse 是一种自定义响应类型,它使用 orjson 库来提高 JSON 数据的序列化性能。orjson 是一个快速且正确的 Python JSON 库,它支持 dataclassdatetimenumpy 等数据类型的序列化。使用 ORJSONResponse 可以提升 API 响应速度,尤其是在处理大量数据时。
在这里插入图片描述

ORJSONResponse 类在 FastAPI 中是用来将响应数据序列化为 JSON 格式并返回给客户端的。它可以处理多种类型的输入数据,包括字典、列表、Pydantic 模型等,并将它们转换为 JSON 格式。然而,并不是所有任意类型的数据都可以被自动序列化为 JSON。可序列化的数据通常包括:

  • 基本数据类型(如整数、浮点数、字符串、布尔值)
  • 列表和元组
  • 字典
  • Pydantic 模型
  • datetime 对象
  • 一些特殊的数据类型,如 UUIDdatetime 等,只要它们有相应的 JSON 序列化方法。

使用 ORJSONResponse 的方法如下:

  1. 首先,需要安装 orjson 库,可以通过 pip install orjson 命令进行安装。
  2. 在 FastAPI 应用中,通过导入 ORJSONResponse 并将其作为路径操作装饰器的 response_class 参数来使用。

示例代码如下:

python">from fastapi import FastAPI
from fastapi.responses import ORJSONResponse

app = FastAPI()

@app.get("/items/", response_class=ORJSONResponse)
async def read_items():
    return [{"item_id": "Foo"}]

在这个例子中,当客户端请求 /items/ 路径时,FastAPI 会使用 ORJSONResponse 来序列化响应数据,并将其发送给客户端。使用 ORJSONResponse 时,响应头中的 Content-Type 将被设置为 application/json,并且这一信息也会被记录在自动生成的 OpenAPI 文档中。

需要注意的是,ORJSONResponse 仅在 FastAPI 中可用,其底层的 Starlette 框架并不支持这一响应类型。此外,ORJSONResponse 是一个较新的功能,可能在某些旧版本的 FastAPI 中不可用。

当然,以下是修改后的示例,包括了如何使用 ORJSONResponse 并展示了预期的输出。

示例 1:基础使用

这个示例展示了如何直接在路由中使用 ORJSONResponse 来返回 JSON 数据。

python">from fastapi import FastAPI
from fastapi.responses import ORJSONResponse

app = FastAPI()

@app.get("/items/", response_class=ORJSONResponse)
async def read_items():
    return [{"item_id": "Foo"}, {"item_id": "Bar"}]

# 预期输出:
# [
#   {"item_id": "Foo"},
#   {"item_id": "Bar"}
# ]

当客户端访问 /items/ 路径时,将收到一个包含两个项目 ID 的 JSON 响应。

示例 2:结合 Pydantic 模型

这个示例展示了如何结合 Pydantic 模型使用 ORJSONResponse,以确保响应数据的类型验证和文档生成。

python">from fastapi import FastAPI
from fastapi.responses import ORJSONResponse
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    item_id: str
    price: float
    tax: float = None

@app.get("/items/", response_class=ORJSONResponse)
async def read_items():
    return Item(item_id="Foo", price=10.5, tax=1.5)

# 预期输出:
# {
#   "item_id": "Foo",
#   "price": 10.5,
#   "tax": 1.5
# }

在这个例子中,Item 是一个 Pydantic 模型,它定义了响应的数据结构。当客户端访问 /items/ 路径时,将收到一个符合 Item 模型的 JSON 响应。

示例 3:自定义响应类

这个示例展示了如何创建一个自定义的响应类,继承自 ORJSONResponse,并使用 orjson 的特定选项来格式化 JSON 输出。

python">from fastapi import FastAPI, Response
from fastapi.responses import ORJSONResponse
import orjson

app = FastAPI()

class CustomORJSONResponse(ORJSONResponse):
    media_type = "application/json"

    def render(self, content: Any) -> bytes:
        assert orjson is not None, "orjson must be installed"
        return orjson.dumps(content, option=orjson.OPT_INDENT_2)

@app.get("/items/", response_class=CustomORJSONResponse)
async def read_items():
    return [{"item_id": "Foo"}, {"item_id": "Bar"}]

# 预期输出:
# [
#   {
#     "item_id": "Foo"
#   },
#   {
#     "item_id": "Bar"
#   }
# ]
# 注意:输出的 JSON 将被格式化,具有缩进和换行符。

在这个例子中,CustomORJSONResponse 类继承自 ORJSONResponse 并重写了 render 方法,使用 orjsonOPT_INDENT_2 选项来美化 JSON 输出。当客户端访问 /items/ 路径时,将收到一个格式化的 JSON 响应。


http://www.niftyadmin.cn/n/5664637.html

相关文章

Koa (下一代web框架) 【Node.js进阶】

koa (中文网) 是基于 Node.js 平台的下一代 web 开发框架,致力于成为应用和 API 开发领域中的一个更小、更富有表现力、更健壮的基石; 利用 async 函数 丢弃回调函数,并增强错误处理,koa 没有任何预置的中间件,可快速…

魔方财务安装指南

本文将详细介绍魔方财务的安装、升级和迁移过程,确保您能够顺利地部署和使用魔方财务系统。 服务器配置一览表 以下是魔方财务1.0.0及更高版本的最低和推荐系统要求: 需求名称推荐配置最低要求OSCentOS/Debian/UbuntuLinux(不要使用window…

CSS学习路线

CSS学习路线大全及面试常见题目可以归纳为以下几个部分: CSS学习路线大全 CSS基础 引入CSS的方式:外部样式表、内部样式表、内联样式。CSS选择器:包括ID选择器、类选择器、标签选择器、后代选择器、子选择器、相邻兄弟选择器、兄弟选择器、…

python 连接数据库,执行查询

代码: import mysql.connector# 连接数据库 conn mysql.connector.connect(host"192.168.1.100",user"root",password"123456",database"abs_bill" )# 创建一个cursor对象 cursor conn.cursor()# 执行查询 cursor.execu…

Python数据分析 Pandas库-初步认识

Python数据分析 Pandas库-初步认识 认识Pandas ​ pandas是一个非常实用的Python工具,我们可以把它想象成一个超级强大的表格处理工具,它比Excel更智能,操作更为简单。pands可以从各种文件格式(CSV、JSON、SQL、Excel&#xff0…

HTML5+CSS3面试题:(第四天)

目录 13.cookie、localStorage、sessionStorage区别 14.简述window对象除 document以外的一些常用子对象,并描述其作用? 15.css中水平垂直居中的方法有哪些? 16.css如何做兼容的? 13.cookie、localStorage、sessionStorage区别 1.先介绍下 cookie…

【bug】通过lora方式微调sdxl inpainting踩坑

报错内容 ValueError: Attempting to unscale FP16 gradients. 报错位置 if accelerator.sync_gradients:params_to_clip (itertools.chain(unet_lora_parameters, text_lora_parameters_one, text_lora_parameters_two)if args.train_text_encoderelse unet_lora_parameters…

QtConcorrent学习、以及与QThread之间的联系

目录 一、QtConcorrent 概述 1、功能 2、特点 3、使用场景 4、QtConcurrent::run 5、应用示例 5、挑战和解决方案 6、QtConcurrent的重要性和价值 二、QFuture 1、主要特点和功能 2、应用示例 三、QtConcorrent与QThread 1、抽象级别和易用性 2. 线程管理和资源利…