溫馨提示×

FastAPI中怎么實現表單數據驗證

小億
141
2024-05-10 16:31:55
欄目: 編程語言

在FastAPI中實現表單數據驗證可以通過Pydantic庫來實現。Pydantic是一個數據驗證庫,可以幫助我們定義數據模型和進行數據校驗。

首先,需要定義一個Pydantic模型來表示表單數據的結構,例如:

from pydantic import BaseModel

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

然后,在FastAPI的路由函數中使用這個模型來驗證表單數據,例如:

from fastapi import FastAPI
from pydantic import BaseModel
from typing import List

app = FastAPI()

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

@app.post("/items/")
async def create_item(item: Item):
    return {"name": item.name, "price": item.price}

在上面的例子中,我們定義了一個包含name、price和description字段的Item模型,并在create_item路由函數中使用這個模型來驗證表單數據。如果客戶端發送的表單數據不符合Item模型的定義,FastAPI會返回一個HTTP 422 Unprocessable Entity錯誤。

通過Pydantic庫和FastAPI的結合,我們可以方便地實現表單數據的驗證,確保接收到的數據符合預期的格式和結構。

2
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女