[FastAPI-23]响应体pydantic dict方法

import typing

from fastapi import FastAPI, Response
from fastapi.responses import JSONResponse
from pydantic import BaseModel

app = FastAPI()

'''
pydantic dict方法
'''

class Item(BaseModel):
    name: str
    description: typing.Union[str, None] = None
    price: float
    tax: float = 10.5

@app.get("/items")
def read_item_name():
    item = Item(name="foo",description="desc",price=9.9)
    # return item.dict(include={"name","tax"})
    '''
    {
      "name": "foo",
      "description": "desc",
      "price": 9.9
    }
    '''
    return item.dict(exclude_unset=True)
    '''
    {
      "name": "foo",
      "description": "desc",
      "price": 9.9
    }
    '''
posted @ 2023-03-25 17:25  LeoShi2020  阅读(90)  评论(0编辑  收藏  举报