[FastAPI-17]模型类嵌套

from fastapi import FastAPI, Body
from pydantic import BaseModel
import typing

app = FastAPI()

'''
{
    "name": "book",
    "description": "python",
    "price": 42.0,
    "tax": 3.2,
    "tags": ["rock","metal","bar"]
}
'''


class Image(BaseModel):
    url: str
    name: str


class ItemTags(BaseModel):
    name: str
    description: str
    price: float
    tax: float
    tags: typing.List[str]


class ItemImage(BaseModel):
    name: str
    description: str
    price: float
    tax: float
    image: Image


class ItemImages(BaseModel):
    name: str
    description: str
    price: float
    tax: float
    images: typing.List[Image]


@app.post("/item")
def create_item(item: ItemTags):
    return item


'''
{
    "name": "book",
    "description": "python",
    "price": 42.0,
    "tax": 3.2,
    "image":{
        "url":"http://example.baidu.com/bag.jpg",
        "name":"Red bag"
    }
}
'''


@app.post("/image")
def create_image(item: ItemImage):
    return item


'''
{
    "name": "book",
    "description": "python",
    "price": 42.0,
    "tax": 3.2,
    "images":[
    {
        "url":"http://example.baidu.com/bag.jpg",
        "name":"Red bag"
    },
    {
        "url":"http://example.baidu.com/bag.jpg",
        "name":"Red bag"
    }]    
}
'''


@app.post("/images")
def create_images(item: ItemImages):
    return item

posted @ 2023-03-24 00:43  LeoShi2020  阅读(21)  评论(0编辑  收藏  举报