jsonable_encoder
在实际应用场景中,可能需要将数据类型(如:Pydantic 模型)转换为与 JSON 兼容的类型(如:字典、列表)
比如: 需要将数据存储在数据库中
为此,FastAPI 提供了一个 jsonable_encoder() 函数
jsonable_encoder 实际上是 FastAPI 内部用来转换数据 的,但它在许多其他场景中很有用
实际栗子
需求
假设有一个仅接收兼容 JSON 数据的数据库 fake_db
例如,它不接收日期时间对象,因为这些对象与 JSON 不兼容
因此,必须将日期时间对象转换为包含 ISO 格式数据的 str
同样,这个数据库不会接收 Pydantic 模型(具有属性的对象),只会接收 dict
使用 jsonable_encoder 将数据转换成 dict
实际代码
"""
# author: 小菠萝测试笔记
# blog: https://www.cnblogs.com/poloyy/
# time: 2021/9/23 1:13 下午
# file: 24_json_encoder.py
"""
from datetime import datetime
from typing import Optional
import uvicorn
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
fake_db = {}
class Item (BaseModel ):
title: str
timestamp: datetime
age: Optional [int ] = None
app = FastAPI()
@app.put("/items/{id}" )
def update_item (id : str , item: Item ):
print (f"item is {item} \nitem type is {type (item)} " )
json_compatible_item_data = jsonable_encoder(item)
fake_db[id ] = json_compatible_item_data
print (f"encoder_data is {json_compatible_item_data} \nencoder_data type is {type (json_compatible_item_data)} " )
return json_compatible_item_data
if __name__ == "__main__" :
uvicorn.run(app="24_json_encoder:app" , host="127.0.0.1" , port=8080 , reload=True , debug=True )
jsonable_encoder 将 Pydantic 模型转换为 dict,并将日期时间转换为 str
它将返回一个 Python 标准数据结构(比如:dict),其中的值和子值都可以和 JSON 兼容
访问 /items/123 接口,查看控制台输出
item is title='string' timestamp=datetime.datetime(2021 , 9 , 23 , 5 , 16 , 36 , 425000 , tzinfo=datetime.timezone.utc) age=24
item type is <class '24 _json_encoder.Item'>
encoder_data is {'title': 'string', 'timestamp': '2021 -09 -23 T05 :16 :36 .425000 +00 :00 ', 'age': 24 }
encoder_data type is <class 'dict'>