fastapi 请求体 - 多个参数 / 字段Field / 嵌套模型
文章目錄
- 1. 混合使用 Path、Query 和請求體參數(shù)
- 2. 多個(gè)請求體參數(shù)
- 3. 請求體中的單一值
- 4. 多個(gè)請求體參數(shù)和查詢參數(shù)
- 5. 嵌入單個(gè)請求體參數(shù)
- 6. 字段
- 7. 嵌套模型
- 7.1 List 字段
- 7.2 子模型作為類型
- 8. 特殊類型校驗(yàn)
- 9. 帶有一組子模型的屬性
- 10. 任意 dict 構(gòu)成的請求體
learn from https://fastapi.tiangolo.com/zh/tutorial/body-multiple-params/
1. 混合使用 Path、Query 和請求體參數(shù)
from fastapi import FastAPI, Path from typing import Optional from pydantic import BaseModel app = FastAPI()class Item1(BaseModel):name: strprice: floatdescription: Optional[str] = Nonetax: Optional[float]@app.put("/items/{item_id}") async def update_item(*,item_id: int = Path(..., title="id of item to get", ge=0, le=1000),q: Optional[str] = None,item: Optional[Item1] = None, ):res = {"item_id": item_id}if q:res.update({"q": q})if item:res.update({"item": item})return res2. 多個(gè)請求體參數(shù)
from pydantic import BaseModelclass Item(BaseModel):name: strprice: floatdescription: Optional[str] = Nonetax: Optional[float] class User(BaseModel):username: strfull_name: Optional[str] = None@app.put("/items/{item_id}") async def update_item(item_id: int, item: Item, user: User):res = {"item_id" : item_id, "item" : item, "user": user}return res- 使用 參數(shù)名稱 最為 key 的 字典傳入
3. 請求體中的單一值
- 傳參時(shí),varname : type = Body(...),如果不這么寫,會(huì)被作為查詢參數(shù) ?varname=xxx
現(xiàn)在可以寫在請求體內(nèi):
4. 多個(gè)請求體參數(shù)和查詢參數(shù)
由于默認(rèn)情況下單一值被解釋為查詢參數(shù),因此你不必顯式地添加 Query,你可以僅執(zhí)行操作:q: str = None
5. 嵌入單個(gè)請求體參數(shù)
如果你只有一個(gè)請求體參數(shù)
@app.put("/items/{item_id}") async def update_item(item_id: int, item: Item):res = {"item_id" : item_id, "item" : item}return res你的請求體需要寫成如下形式:
如果你想寫成 帶 key 的 json 形式,添加一個(gè)傳入?yún)?shù) embed,item: Item = Body(..., embed=True)
6. 字段
可以使用 Pydantic 的 Field 在 Pydantic 模型內(nèi)部聲明校驗(yàn)和元數(shù)據(jù)
from fastapi import FastAPI, Path, Body from typing import Optional from pydantic import BaseModel, Field app = FastAPI()class Item(BaseModel):name: strprice: float = Field(..., gt=0, description="price must be greater than 0")description: Optional[str] = Field(None, title="description of item", max_length=30)tax: Optional[float] = None@app.put("/items/{item_id}") async def update_item(item_id: int, item: Item = Body(..., embed=True)):res = {"item_id" : item_id, "item" : item}return resField 的工作方式和 Query、Path 和 Body 相同,包括它們的參數(shù)等等也完全相同
- 注意,from pydantic import Field
7. 嵌套模型
7.1 List 字段
將一個(gè)屬性定義為擁有子元素的類型,如 list
class Item(BaseModel):name: strprice: float = Field(..., gt=0, description="price must be greater than 0")description: Optional[str] = Field(None, title="description of item", max_length=30)tax: Optional[float] = Nonetags: list = [] # 沒有聲明元素類型- 具有子類型的 List,from typing import List
7.2 子模型作為類型
from fastapi import FastAPI, Path, Body from typing import Optional, List, Set from pydantic import BaseModel, Field app = FastAPI()class Image(BaseModel):url:strname: strclass Item(BaseModel):name: strprice: float = Field(..., gt=0, description="price must be greater than 0")description: Optional[str] = Field(None, title="description of item", max_length=30)tax: Optional[float] = Nonetags: Set[str] = []image: Optional[Image] = None@app.put("/items/{item_id}") async def update_item(item_id: int, item: Item = Body(..., embed=True)):res = {"item_id" : item_id, "item" : item}return res8. 特殊類型校驗(yàn)
- HttpUrl,檢查是不是有效的 URL
則上面的輸入應(yīng)改的地方 "url":"http://www.michael.com",否則不是有效的 URL
9. 帶有一組子模型的屬性
- 更改為 image: Optional[List[Image]] = None
輸入需要改為
10. 任意 dict 構(gòu)成的請求體
from typing import Optional, List, Set, Dict @app.post("/index-weights/") async def create_index_weights(weights: Dict[int, float]): # key 為 int, value 為浮點(diǎn)return weights請記住 JSON 僅支持將 str 作為鍵。 但是 Pydantic 具有自動(dòng)轉(zhuǎn)換數(shù)據(jù)的功能。
總結(jié)
以上是生活随笔為你收集整理的fastapi 请求体 - 多个参数 / 字段Field / 嵌套模型的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2021年算法工作总结
- 下一篇: LeetCode 1992. 找到所有的