Pydantic 模型 是一种基于 Python 的 数据验证和数据解析工具,它使用 Python 的类型注解(type hints)来定义数据结构,并自动进行校验、转换和序列化。

它是 FastAPI 的核心组成部分,用于:

  • 校验请求数据(如 JSON 请求体)

  • 自动生成文档

  • 简化数据模型定义

from pydantic import BaseModel, EmailStr

class User(BaseModel):
username: str
email: EmailStr
age: int

解释:

 

  • username 必须是字符串

  • email 必须是合法邮箱地址(EmailStr 是 Pydantic 内置类型)

  • age 必须是整数

当传入数据如下:

{
“username”: “alice”,
“email”: “alice@example.com”,
“age”: 25
}

校验成功,创建模型实例。

但如果是:

{
“username”: “bob”,
“email”: “not-an-email”,
“age”: “twenty”
}

{
“username”: “alice”,
“email”: “alice@example.com”,
“age”: 25,
“sex”: “男”
}

自动抛出错误(422 Unprocessable Entity):

{
“detail”: [
{
“loc”: [“body”, “email”],
“msg”: “value is not a valid email address”,
“type”: “value_error.email”
},
{
“loc”: [“body”, “age”],
“msg”: “value is not a valid integer”,
“type”: “type_error.integer”
}
]
}

Pydantic 模型就是 FastAPI 中用于定义和校验数据结构的工具。

如何允许额外字段?

from pydantic import BaseModel, EmailStr, Extra

class User(BaseModel):
username: str
email: EmailStr
age: int

class Config:
extra = Extra.allow

 

作者 admin

百度广告效果展示