FastAPI 进阶知识(二) JSON兼容编码


作者:麦克煎蛋   出处:https://www.cnblogs.com/mazhiyong/ 转载请保留这段声明,谢谢!

 

在进行数据存储或者传输的时候,有时候我们需要把数据(比如Pydantic模型)转换成JSON兼容的格式(如dict、list等)。

FastAPI提供了 jsonable_encoder 函数来实现。

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


app = FastAPI()


@app.put("/items/{id}")
def update_item(id: str, item: Item):
    json_compatible_item_data = jsonable_encoder(item) print(json_compatible_item_data)

在上面的示例中,如果Request Body为:

{
    "title": "title",
    "timestamp": "2017-11-23 16:10:10"
}

那么打印结果为:

{'title': 'title', 'timestamp': '2017-11-23T16:10:10', 'description': None}

这里 jsonable_encoderdatetime 转换成了字符串,而把Pydantic模型转换成了dict格式。

其他类型的数据转换可自行尝试。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM