当前位置: 首页 > article >正文

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

在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 参数来使用。

示例代码如下:

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 数据。

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,以确保响应数据的类型验证和文档生成。

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 输出。

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.kler.cn/news/311020.html

相关文章:

  • Ubuntu 22.04上安装Python 3.10.x
  • Element走马灯组件循环播放两个页面是方向不一致
  • 网络安全实训九(域环境的创建及其信息收集)
  • 图像到图像的翻译
  • General OCR Theory: Towards OCR-2.0 via a Unified End-to-end Model
  • 用 ReactPHP 实现图片上传加速:让并发上传实现真正的高效
  • 软件测试工程师面试整理-操作系统与网络基础
  • 人工智能——猴子摘香蕉问题
  • centos中yum方式部署Jenkins
  • 【Linux取经之路】编译器gcc/g++的使用 调试器gdb的使用
  • OceanBase 运维管理工具 OCP 4.x 升级:聚焦高可用、易用性及可观测性
  • Vscode搭配latex简易教程
  • file的判断和获取,创建和删除
  • C++使用Socket编程实现一个简单的HTTP服务器
  • 掌握MySQL性能监控 · performance_schema 使用快速入门
  • Linux_bash的一些特殊符号
  • 聚观早报 | 极越07正式上市;宝骏云海正式上市
  • Laya2.x出包alipay小游戏
  • Java后端框架---Spring
  • 每日一问:C++ 如何实现继承、封装和多态
  • 随着访问范围的扩大 OpenAI o1-mini 现已向免费用户开放
  • 大模型训练数据库Common Crawl
  • MySQL常用的函数
  • 函数的定义与使用
  • 【Hot100】LeetCode—169. 多数元素
  • 常见汇编指令
  • C++系列-谓词predicate
  • AWTK fscript 中的 CRC函数
  • 转行大模型开发:挑战与机遇,如何有效学习以实现职业转变
  • 第二证券:移动物联网迎政策助力 稀土价格有望持续回暖