import typing
from fastapi import FastAPI, Response
from fastapi.responses import JSONResponse
from pydantic import BaseModel
app = FastAPI()
'''
过滤响应数据
- 只包含 response_model_include={"name"}
- 排除 response_model_exclude={"tax"}
- 过滤没有设置值 response_model_exclude_unset=True
{
"name": "foo",
"price": 50.2
}
- 过滤默认值 response_model_exclude_defaults=True
- 过滤空值 response_model_exclude_none=True
'''
class Item(BaseModel):
name: str
description: typing.Union[str, None] = None
price: float
tax: float = 10.5
items = {
"foo": {"name": "foo", "price": 50.2},
"bar": {"name": "Bar", "description": "This Bar fighter", "price": 62, "tax": 20.2},
"baz": {
"name": "Baz",
"description": "There goes my baz",
"price": 50.2,
"tax": 10.5
}
}
@app.get("/items/{name}",
response_model=Item,
# response_model_include={"name","tax"},
# response_model_exclude={"tax"},
response_model_exclude_unset=True,
# response_model_exclude_defaults=True,
# response_model_exclude_none=True
)
def read_item_name(name:str):
return items[name]