#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
# 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):
# 1、打印刚传进来的数据和类型
print(f"item is {item}\nitem type is {type(item)}")
# 2、调用 jsonable_encoder 将 Pydantic Model 转成 Dict
json_compatible_item_data = jsonable_encoder(item)
# 3、模拟将数据落库操作
fake_db[id] = json_compatible_item_data
# 4、打印转换后的数据和类型
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)
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-23T05:16:36.425000+00:00', 'age': 24}
encoder_data type is <class 'dict'>