温馨提示×

FastAPI中怎么实现表单数据验证

小亿
86
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的结合,我们可以方便地实现表单数据的验证,确保接收到的数据符合预期的格式和结构。

0