FastAPI 数据处理:使用 jsonable_encoder()
转换 Pydantic model 为 JSON
在 FastAPI 中,jsonable_encoder()
函数将 Pydantic 模型转换为 JSON 兼容的 Python 数据类型,如字典或列表。转换后的数据结构能够与标准 JSON 格式兼容,适用于与外部系统的数据交换。文章展示了如何使用 jsonable_encoder()
将 Pydantic 模型转换为 Python 数据结构,并将其存储到模拟数据库中。此方法确保数据能够顺利转换并处理为 JSON 格式,便于后续操作。
文章目录
以下示例中使用的 Python 版本为 Python 3.10.15
,FastAPI 版本为 0.115.4
。
一 代码示例
from datetime import datetime
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
class Item(BaseModel):
title: str
timestamp: datetime
description: str | None = None
app = FastAPI()
@app.put("/items/{id}")
def update_item(id: str, item: Item):
fake_db = {}
json_compatible_item_data = jsonable_encoder(item)
fake_db[id] = json_compatible_item_data
return fake_db
运行代码文件 chapter24.py 来启动应用:
$ uvicorn chapter24:app --reload
在 SwaggerUI 中可以查看在线文档:http://127.0.0.1:8000/docs
。
二 函数 jsonable_encoder()
FastAPI 提供了 jsonable_encoder()
函数,可将 Pydantic 模型(Pydantic model)转换为 JSON 兼容的数据类型(如 dict
、list
等)。
def update_item(id: str, item: Item):
fake_db = {}
json_compatible_item_data = jsonable_encoder(item)
fake_db[id] = json_compatible_item_data
return fake_db
jsonable_encoder
实际上是 FastAPI 内部用于转换数据的工具,将 Pydantic 模型转换为 JSON 兼容的格式后,可以直接使用 Python 标准库中的 json.dumps()
。它返回一个 Python 标准数据结构(如 dict
),该结构与 JSON 兼容。转换之后的数据结构如下:
三 完整代码示例
from datetime import datetime
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
class Item(BaseModel):
title: str
timestamp: datetime
description: str | None = None
app = FastAPI()
@app.put("/items/{id}")
def update_item(id: str, item: Item):
fake_db = {}
json_compatible_item_data = jsonable_encoder(item)
fake_db[id] = json_compatible_item_data
return fake_db
四 源码地址
五 参考
[1] FastAPI 文档
[2] Python 官网