fastapi(七)Body

我们已经提到过Path以及Query,下面来看看更好的对于请求正文的声明

body-多个参数
混合Path,Query和请求正文参数
eg:

from fastapi import FastAPI, Path
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None


@app.put("/items/{item_id}")
async def update_item(
    *,
    item_id: int = Path(..., title="The ID of the item to get", ge=0, le=1000),
    q: str = None,
    item: Item = None,
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    if item:
        results.update({"item": item})
    return results

多个请求正文参数

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None


class User(BaseModel):
    username: str
    full_name: str = None


@app.put("/items/{item_id}")
async def update_item(*, item_id: int, item: Item, user: User):
    results = {"item_id": item_id, "item": item, "user": user}
    return results

请求body:

{
    "item": {
        "name": "Foo",
        "description": "The pretender",
        "price": 42.0,
        "tax": 3.2
    },
    "user": {
        "username": "dave",
        "full_name": "Dave Grohl"
    }
}

body中的单个值参数
因为在fastapi中默认将单个值识别为查询参数所以
fastapi提供了Body,类似Path、Query
。。。
@app.put("/items/{item_id}")
async def update_item(
*, item_id: int, item: Item, user: User, importance: int = Body(…)
):
。。。

然后请求主体就是:
{
“item”: {
“name”: “Foo”,
“description”: “The pretender”,
“price”: 42.0,
“tax”: 3.2
},
“user”: {
“username”: “dave”,
“full_name”: “Dave Grohl”
},
“importance”: 5
}

嵌入单个请求主体参数
当只有单个请求主体参数时,默认fastapi只会直接读取其主体。
但是当想要一个json带有key,item在请求正文中,可以使用embed

from fastapi import Body, FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None


@app.put("/items/{item_id}")
async def update_item(*, item_id: int, item: Item = Body(..., embed=True)):
    results = {"item_id": item_id, "item": item}
    return results

请求主体为:

{
    "item": {
        "name": "Foo",
        "description": "The pretender",
        "price": 42.0,
        "tax": 3.2
    }
}

body-fields
在pydantic模型内部使用Field来声明验证和metadata
eg:

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

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str = Field(None, title="The description of the item", max_length=300)
    price: float = Field(..., gt=0, description="The price must be greater than zero")
    tax: float = None


@app.put("/items/{item_id}")
async def update_item(*, item_id: int, item: Item = Body(..., embed=True)):
    results = {"item_id": item_id, "item": item}
    return results

额外的json schema
在field,path,query,body中,可以声明额外的部分。
这些参数将被添加到json格式输出。
eg:

from fastapi import Body, FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None


@app.put("/items/{item_id}")
async def update_item(
    *,
    item_id: int,
    item: Item = Body(
        ...,
        example={
            "name": "Foo",
            "description": "A very nice Item",
            "price": 35.4,
            "tax": 3.2,
        },
    )
):
    results = {"item_id": item_id, "item": item}
    return results

然后在docs中显示为:
在这里插入图片描述
Body-嵌套模型
List fields
可以定义一个属性是子类型,例如list
eg:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None
    tags: list = []


@app.put("/items/{item_id}")
async def update_item(*, item_id: int, item: Item):
    results = {"item_id": item_id, "item": item}
    return results

其中tags,可以进行子类型验证
eg:
from typing import List

tags:List[str]=[]

拥有子类型的类型包括:list,dict,tuple等。
set type
from typing imoprt Set

tags:Set[str]=set()

嵌套模型

eg:

from typing import Set

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


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


class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None
    tags: Set[str] = []
    image: Image = None

特别的类型和验证
除了常规的单类型,str,int,float等,你可以使用更复杂的继承自str的单类型。
可以在Pydantic exotic types
中查看更多的类型。
例如,在字段中有一个url field,我们可以将它声明为HttpUrl 去代替str

from pydantic import BaseModel, HttpUrl
class Image(BaseModel):
    url: HttpUrl
    name: str
    

这个url字段将被验证是否是正确的Url。
list中也可使用子模型。
images: List[Image] = None

注意:如果事前不知道传送的body中key是什么,可以直接使用
async def create_index_weights(weights: Dict[int, float]):…
body中拥有int类型的key和float类型的值。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值