Walidacja pydantyczna

Wymuszenie typu i walidacja modelu.

Spróbuj w Edytorze

Przegląd

Pydantic pozwala klasom danych Pythona automatycznie mutować zasadniczo nietypowane konfiguracje sieciowe na reprezentacje o typie.

Chroni to stan systemu przy użyciu solidnych ograniczeń typu.

Dane wyjściowe kodu i wykonania

Deklaruje ścisły model użytkownika schematu dla ładunków walidacyjnych.

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))
Wyjście terminala
--- 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
}

Wdrażanie krok po kroku

  • Ochrona punktu końcowego API
  • Walidacja schematu konfiguracji
  • Interfejs bazy danych

Często zadawane pytania

Powiązane tematy