import random
from fastapi import FastAPI
from pydantic import Field, BaseModel
import typing
app = FastAPI()
'''
请求体的每一个字段需要单独校验
name 长度最少3位
price 不少于10
tags 元素不重复,元素个数
{
"name": "book",
"description": "python",
"price": 42.0,
"tax": 3.2,
"tags": ["rock","metal","bar"]
}
'''
class ItemTags(BaseModel):
name: str = Field(min_length=3, example="Tom")
description: str
price: float = Field(ge=10, example=18)
tax: float
tags: typing.List[str] = Field(min_items=3, max_items=5, unique_items=True)
# 默认随机值
discount: int = Field(default_factory=lambda: random.randint(1, 9))
@app.post("/item")
def create_item(item: ItemTags):
return item