python进阶-Pydantic模型

1. 什么是 Pydantic

Pydantic 是一个 Python 库,用来:

  • 定义数据结构
  • 自动校验数据
  • 自动类型转换
  • 生成结构化数据(字典、JSON)
  • 配合 FastAPI 实现接口参数校验

一句话:Pydantic 模型 = 带校验规则的数据类。

2. 核心作用

  1. 数据校验:类型不对、格式不对直接报错
  2. 类型自动转换:字符串数字 → int/float
  3. 结构化数据:接口入参、出参统一格式
  4. 自动生成文档 :FastAPI 自动用它生成 /docs
  5. ORM 模型转换:数据库对象 ↔ 接口数据

3. 基础使用

3.1 安装

复制代码
pip install pydantic

3.2 定义最简单的模型

复制代码
from pydantic import BaseModel

class User(BaseModel):
    name: str
    age: int
    email: str

这就是一个 Pydantic 模型

4. 自动校验 & 自动类型转换

复制代码
user = User(name="张三", age="20", email="xxx@qq.com")
print(user.age)  # 输出 int 20(自动转)

传错类型会直接报错:

复制代码
user = User(name="张三", age="abc", email="xxx")
# 直接抛出 ValidationError

5. 常用字段校验

复制代码
from pydantic import BaseModel, Field, EmailStr

class User(BaseModel):
    name: str = Field(..., min_length=2, max_length=20)
    age: int = Field(..., ge=18, le=100)
    email: EmailStr  # 自动校验邮箱格式

常用规则:

  • min_length / max_length:长度
  • ge:大于等于
  • gt:大于
  • le:小于等于
  • lt:小于
  • ...:表示必填

6. 模型继承

复制代码
class UserBase(BaseModel):
    name: str
    age: int

class UserCreate(UserBase):
    password: str

class UserOut(UserBase):
    id: int

实际开发中非常常用:

  • Base:公共字段
  • Create:创建时需要的字段
  • Out:返回给前端的字段

7. 模型转字典 / JSON

复制代码
user = User(name="张三", age=20, email="xxx@qq.com")

# 转字典
user.dict()

# 转 JSON 字符串
user.json()

8. 嵌套模型

复制代码
class Address(BaseModel):
    city: str
    street: str

class User(BaseModel):
    name: str
    address: Address  # 嵌套模型

9. 列表、泛型

复制代码
from typing import List

class UserOut(BaseModel):
    id: int
    name: str

class UserList(BaseModel):
    total: int
    items: List[UserOut]

10. ORM 模式

FastAPI + SQLAlchemy 必用:

复制代码
class UserOut(BaseModel):
    id: int
    name: str

    class Config:
        orm_mode = True

这样就能直接:

复制代码
user_out = UserOut.from_orm(db_user)

11. 可选字段 & 默认值

复制代码
class User(BaseModel):
    name: str
    age: int | None = None  # 可选
    is_vip: bool = False    # 默认值

12. Pydantic 在 FastAPI 中的作用

  1. 请求体校验

    @app.post("/user")
    def create_user(user: User):
    return user

  2. 查询参数校验

  3. 路径参数校验

  4. 自动生成接口文档 /docs

  5. 统一返回格式

相关推荐
星云穿梭11 小时前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵12 小时前
用 Pygame 实现 15 puzzle
python·数学·游戏
黄忠17 小时前
大模型之LangGraph技术体系
python·llm
hboot1 天前
AI工程师第二课 - 数据处理
人工智能·python·数据分析
用户8356290780511 天前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
用户8356290780512 天前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
黄忠2 天前
01-系统架构设计-LangGraph状态机与多源异构RAG
python
zzzzzz3102 天前
假如我是掘金管理员,我先给评论区装个'代码审查'系统
python·程序员·机器人
砍材农夫2 天前
python环境|conda安装和使用(2)
后端·python
程序员龙叔2 天前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试