日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)FastAPI教程:FastAPI教程請(qǐng)求體-字段

與使用 Query、Path 和 Body 在路徑操作函數(shù)中聲明額外的校驗(yàn)和元數(shù)據(jù)的方式相同,你可以使用 Pydantic 的 Field 在 Pydantic 模型內(nèi)部聲明校驗(yàn)和元數(shù)據(jù)。

成都創(chuàng)新互聯(lián)公司是一家專注于成都做網(wǎng)站、成都網(wǎng)站建設(shè)、成都外貿(mào)網(wǎng)站建設(shè)與策劃設(shè)計(jì),饒河網(wǎng)站建設(shè)哪家好?成都創(chuàng)新互聯(lián)公司做網(wǎng)站,專注于網(wǎng)站建設(shè)10余年,網(wǎng)設(shè)計(jì)領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:饒河等地區(qū)。饒河做網(wǎng)站價(jià)格咨詢:028-86922220

導(dǎo)入 Field

首先,你必須導(dǎo)入它:

from typing import Optional

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

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Optional[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: Optional[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

Warning

注意,F(xiàn)ield 是直接從 pydantic 導(dǎo)入的,而不是像其他的(Query,Path,Body 等)都從 fastapi 導(dǎo)入。

聲明模型屬性

然后,你可以對(duì)模型屬性使用 Field:

from typing import Optional

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

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Optional[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: Optional[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

Field 的工作方式和 Query、Path 和 Body 相同,包括它們的參數(shù)等等也完全相同。

技術(shù)細(xì)節(jié)

實(shí)際上,Query、Path 和其他你將在之后看到的類,創(chuàng)建的是由一個(gè)共同的 Params 類派生的子類的對(duì)象,該共同類本身又是 Pydantic 的 FieldInfo 類的子類。

Pydantic 的 Field 也會(huì)返回一個(gè) FieldInfo 的實(shí)例。

Body 也直接返回 FieldInfo 的一個(gè)子類的對(duì)象。還有其他一些你之后會(huì)看到的類是 Body 類的子類。

請(qǐng)記住當(dāng)你從 fastapi 導(dǎo)入 Query、Path 等對(duì)象時(shí),他們實(shí)際上是返回特殊類的函數(shù)。

Tip

注意每個(gè)模型屬性如何使用類型、默認(rèn)值和 Field 在代碼結(jié)構(gòu)上和路徑操作函數(shù)的參數(shù)是相同的,區(qū)別是用 Field 替換Path、Query 和 Body。

添加額外信息

你可以在 Field、Query、Body 中聲明額外的信息。這些信息將包含在生成的 JSON Schema 中。

你將在文檔的后面部分學(xué)習(xí)聲明示例時(shí),了解到更多有關(guān)添加額外信息的知識(shí)。

總結(jié)

你可以使用 Pydantic 的 Field 為模型屬性聲明額外的校驗(yàn)和元數(shù)據(jù)。

你還可以使用額外的關(guān)鍵字參數(shù)來傳遞額外的 JSON Schema 元數(shù)據(jù)。


網(wǎng)站欄目:創(chuàng)新互聯(lián)FastAPI教程:FastAPI教程請(qǐng)求體-字段
文章分享:http://www.dlmjj.cn/article/coededp.html