Pydantic 验证

类型强制和模型验证。

在编辑器中尝试

概述

Pydantic 允许 Python 数据类自动将根本上无类型的网络配置转变为类型化表示。

这使用稳健的类型约束来保护系统状态。

代码和执行输出

声明用于验证有效负载的严格模式用户模型。

from pydantic import BaseModel, EmailStr, Field
from typing import List, Optional
import json

class User(BaseModel):
    id: int
    name: str = Field(min_length=2)
    email: EmailStr
    tags: List[str] = []
    is_active: bool = True

# Simulating an API response with mixed types
incoming_data = {
    "id": "123",       # string gets coerced to int
    "name": "Alice",
    "email": "alice@example.com",
    "tags": ("python", "developer") # tuple gets coerced to list
}

# Validate and instantiate
user = User(**incoming_data)

print("--- Validated Pydantic Model ---")
print(repr(user))
print("\n--- Exported to JSON ---")
print(user.model_dump_json(indent=2))
端子输出
--- Validated Pydantic Model ---
User(id=123, name='Alice', email='alice@example.com', tags=['python', 'developer'], is_active=True)

--- Exported to JSON ---
{
  "id": 123,
  "name": "Alice",
  "email": "alice@example.com",
  "tags": [
    "python",
    "developer"
  ],
  "is_active": true
}

逐步实施

  • API端点保护
  • 配置模式验证
  • 数据库接口

常见问题解答

相关主题