Pydantic est une bibliothèque Python qui simplifie la validation des données à l'aide d'indices de type. Il garantit l'intégrité des données et offre un moyen simple de créer des modèles de données avec vérification et validation automatiques du type.
Dans les applications logicielles, une validation fiable des données est cruciale pour éviter les erreurs, les problèmes de sécurité et les comportements imprévisibles.
Ce guide fournit les meilleures pratiques d'utilisation de Pydantic dans les projets Python, couvrant la définition du modèle, la validation des données, la gestion des erreurs et l'optimisation des performances.
Pour installer Pydantic, utilisez pip, l'installateur du package Python, avec la commande :
pip install pydantic
Cette commande installe Pydantic et ses dépendances.
Créez des modèles Pydantic en créant des classes qui héritent de BaseModel. Utilisez les annotations de type Python pour spécifier le type de chaque champ :
from pydantic import BaseModel class User(BaseModel): id: int name: str email: str
Pydantic prend en charge différents types de champs, notamment int, str, float, bool, list et dict. Vous pouvez également définir des modèles imbriqués et des types personnalisés :
from typing import List, Optional from pydantic import BaseModel class Address(BaseModel): street: str city: str zip_code: Optional[str] = None class User(BaseModel): id: int name: str email: str age: Optional[int] = None addresses: List[Address]
Une fois que vous avez défini un modèle Pydantic, créez des instances en fournissant les données requises. Pydantic validera les données et générera des erreurs si un champ ne répond pas aux exigences spécifiées :
user = User( id=1, name="John Doe", email="john.doe@example.com", addresses=[{"street": "123 Main St", "city": "Anytown", "zip_code": "12345"}] ) print(user) # Output: # id=1 name='John Doe' email='john.doe@example.com' age=None addresses=[Address(street='123 Main St', city='Anytown', zip_code='12345')]
Les modèles Pydantic utilisent des annotations de type Python pour définir les types de champs de données.
Ils prennent en charge différents types intégrés, notamment :
Exemple :
from typing import List, Dict, Optional, Union from pydantic import BaseModel class Item(BaseModel): name: str price: float tags: List[str] metadata: Dict[str, Union[str, int, float]] class Order(BaseModel): order_id: int items: List[Item] discount: Optional[float] = None
En plus des types intégrés, vous pouvez définir des types personnalisés à l'aide des fonctions conint, constr et d'autres fonctions de contrainte de Pydantic.
Celles-ci vous permettent d'ajouter des règles de validation supplémentaires, telles que des contraintes de longueur sur les chaînes ou des plages de valeurs pour les entiers.
Exemple :
from pydantic import BaseModel, conint, constr class Product(BaseModel): name: constr(min_length=2, max_length=50) quantity: conint(gt=0, le=1000) price: float product = Product(name="Laptop", quantity=5, price=999.99)
Par défaut, les champs d'un modèle Pydantic sont obligatoires sauf s'ils sont explicitement marqués comme facultatifs.
Si un champ obligatoire est manquant lors de l'instanciation du modèle, Pydantic générera une ValidationError.
Exemple :
from pydantic import BaseModel class User(BaseModel): id: int name: str email: str user = User(id=1, name="John Doe") # Output # Field required [type=missing, input_value={'id': 1, 'name': 'John Doe'}, input_type=dict]
Les champs peuvent être rendus facultatifs en utilisant Facultatif dans le module de saisie et en fournissant une valeur par défaut.
Exemple :
from pydantic import BaseModel from typing import Optional class User(BaseModel): id: int name: str email: Optional[str] = None user = User(id=1, name="John Doe")
Dans cet exemple, l'e-mail est facultatif et la valeur par défaut est Aucun s'il n'est pas fourni.
Pydantic permet aux modèles d'être imbriqués les uns dans les autres, permettant ainsi des structures de données complexes.
Les modèles imbriqués sont définis comme des champs d'autres modèles, garantissant l'intégrité et la validation des données à plusieurs niveaux.
Exemple :
from pydantic import BaseModel from typing import Optional, List class Address(BaseModel): street: str city: str zip_code: Optional[str] = None class User(BaseModel): id: int name: str email: str addresses: List[Address] user = User( id=1, name="John Doe", email="john.doe@example.com", addresses=[{"street": "123 Main St", "city": "Anytown"}] )
Lorsque vous travaillez avec des modèles imbriqués, il est important de :
Pydantic comprend un ensemble de validateurs intégrés qui gèrent automatiquement les tâches courantes de validation des données.
Ces validateurs incluent :
Ces validateurs simplifient le processus visant à garantir l'intégrité et la conformité des données au sein de vos modèles.
Voici quelques exemples illustrant les validateurs intégrés :
à partir de l'importation pydantique BaseModel, EmailStr, conint, constr
class User(BaseModel): id: conint(gt=0) # id must be greater than 0 name: constr(min_length=2, max_length=50) # name must be between 2 and 50 characters email: EmailStr # email must be a valid email address age: conint(ge=18) # age must be 18 or older user = User(id=1, name="John Doe", email="john.doe@example.com", age=25)
Dans cet exemple, le modèle Utilisateur utilise des validateurs intégrés pour garantir que l'identifiant est supérieur à 0, que le nom comporte entre 2 et 50 caractères, que l'e-mail est une adresse e-mail valide et que l'âge est de 18 ans ou plus.
Pour pouvoir utiliser le validateur d'e-mails, vous devez installer une extension pour pydantic :
pip install pydantic[email]
Pydantic allows you to define custom validators for more complex validation logic.
Custom validators are defined using the @field_validator decorator within your model class.
Example of a custom validator:
from pydantic import BaseModel, field_validator class Product(BaseModel): name: str price: float @field_validator('price') def price_must_be_positive(cls, value): if value <= 0: raise ValueError('Price must be positive') return value product = Product(name="Laptop", price=999.99)
Here, the price_must_be_positive validator ensures that the price field is a positive number.
Custom validators are registered automatically when you define them within a model using the @field_validator decorator. Validators can be applied to individual fields or across multiple fields.
Example of registering a validator for multiple fields:
from pydantic import BaseModel, field_validator class Person(BaseModel): first_name: str last_name: str @field_validator('first_name', 'last_name') def names_cannot_be_empty(cls, value): if not value: raise ValueError('Name fields cannot be empty') return value person = Person(first_name="John", last_name="Doe")
In this example, the names_cannot_be_empty validator ensures that both the first_name and last_name fields are not empty.
Pydantic models can be customized using an inner Config class.
This class allows you to set various configuration options that affect the model's behavior, such as validation rules, JSON serialization, and more.
Example of a Config class:
from pydantic import BaseModel class User(BaseModel): id: int name: str email: str class Config: str_strip_whitespace = True # Strip whitespace from strings str_min_length = 1 # Minimum length for any string field user = User(id=1, name=" John Doe ", email="john.doe@example.com") print(user) # Output: # id=1 name='John Doe' email='john.doe@example.com'
In this example, the Config class is used to strip whitespace from string fields and enforce a minimum length of 1 for any string field.
Some common configuration options in Pydantic's Config class include:
When Pydantic finds data that doesn't conform to the model's schema, it raises a ValidationError.
This error provides detailed information about the issue, including the field name, the incorrect value, and a description of the problem.
Here's an example of how default error messages are structured:
from pydantic import BaseModel, ValidationError, EmailStr class User(BaseModel): id: int name: str email: EmailStr try: user = User(id='one', name='John Doe', email='invalid-email') except ValidationError as e: print(e.json()) # Output: # [{"type":"int_parsing","loc":["id"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"one","url":"https://errors.pydantic.dev/2.8/v/int_parsing"},{"type":"value_error","loc":["email"],"msg":"value is not a valid email address: An email address must have an @-sign.","input":"invalid-email","ctx":{"reason":"An email address must have an @-sign."},"url":"https://errors.pydantic.dev/2.8/v/value_error"}]
In this example, the error message will indicate that id must be an integer and email must be a valid email address.
Pydantic allows you to customize error messages for specific fields by raising exceptions with custom messages in validators or by setting custom configurations.
Here’s an example of customizing error messages:
from pydantic import BaseModel, ValidationError, field_validator class Product(BaseModel): name: str price: float @field_validator('price') def price_must_be_positive(cls, value): if value <= 0: raise ValueError('Price must be a positive number') return value try: product = Product(name='Laptop', price=-1000) except ValidationError as e: print(e.json()) # Output: # [{"type":"value_error","loc":["price"],"msg":"Value error, Price must be a positive number","input":-1000,"ctx":{"error":"Price must be a positive number"},"url":"https://errors.pydantic.dev/2.8/v/value_error"}]
In this example, the error message for price is customized to indicate that it must be a positive number.
Effective error reporting involves providing clear, concise, and actionable feedback to users or developers.
Here are some best practices:
Examples of best practices in error reporting:
from pydantic import BaseModel, ValidationError, EmailStr import logging logging.basicConfig(level=logging.INFO) class User(BaseModel): id: int name: str email: EmailStr def create_user(data): try: user = User(**data) return user except ValidationError as e: logging.error("Validation error: %s", e.json()) return {"error": "Invalid data provided", "details": e.errors()} user_data = {'id': 'one', 'name': 'John Doe', 'email': 'invalid-email'} response = create_user(user_data) print(response) # Output: # ERROR:root:Validation error: [{"type":"int_parsing","loc":["id"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"one","url":"https://errors.pydantic.dev/2.8/v/int_parsing"},{"type":"value_error","loc":["email"],"msg":"value is not a valid email address: An email address must have an @-sign.","input":"invalid-email","ctx":{"reason":"An email address must have an @-sign."},"url":"https://errors.pydantic.dev/2.8/v/value_error"}] # {'error': 'Invalid data provided', 'details': [{'type': 'int_parsing', 'loc': ('id',), 'msg': 'Input should be a valid integer, unable to parse string as an integer', 'input': 'one', 'url': 'https://errors.pydantic.dev/2.8/v/int_parsing'}, {'type': 'value_error', 'loc': ('email',), 'msg': 'value is not a valid email address: An email address must have an @-sign.', 'input': 'invalid-email', 'ctx': {'reason': 'An email address must have an @-sign.'}}]}
In this example, validation errors are logged, and a user-friendly error message is returned, helping maintain application stability and providing useful feedback to the user.
Lazy initialization is a technique that postpones the creation of an object until it is needed.
In Pydantic, this can be useful for models with fields that are costly to compute or fetch. By delaying the initialization of these fields, you can reduce the initial load time and improve performance.
Example of lazy initialization:
from pydantic import BaseModel from functools import lru_cache class DataModel(BaseModel): name: str expensive_computation: str = None @property @lru_cache(maxsize=1) def expensive_computation(self): # Simulate an expensive computation result = "Computed Value" return result data_model = DataModel(name="Test") print(data_model.expensive_computation)
In this example, the expensive_computation field is computed only when accessed for the first time, reducing unnecessary computations during model initialization.
Pydantic models automatically validate data during initialization.
However, if you know that certain data has already been validated or if validation is not necessary in some contexts, you can disable validation to improve performance.
This can be done using the model_construct method, which bypasses validation:
Example of avoiding redundant validation:
from pydantic import BaseModel class User(BaseModel): id: int name: str email: str # Constructing a User instance without validation data = {'id': 1, 'name': 'John Doe', 'email': 'john.doe@example.com'} user = User.model_construct(**data)
In this example, User.model_construct is used to create a User instance without triggering validation, which can be useful in performance-critical sections of your code.
When dealing with large datasets or high-throughput systems, efficiently parsing raw data becomes critical.
Pydantic provides the model_validate_json method, which can be used to parse JSON or other serialized data formats directly into Pydantic models.
Example of efficient data parsing:
from pydantic import BaseModel class User(BaseModel): id: int name: str email: str json_data = '{"id": 1, "name": "John Doe", "email": "john.doe@example.com"}' user = User.model_validate_json(json_data) print(user)
In this example, model_validate_json is used to parse JSON data into a User model directly, providing a more efficient way to handle serialized data.
Pydantic models can be configured to validate data only when necessary.
The validate_default and validate_assignment options in the Config class control when validation occurs, which can help improve performance:
Example configuration:
from pydantic import BaseModel class User(BaseModel): id: int name: str email: str class Config: validate_default = False # Only validate fields set during initialization validate_assignment = True # Validate fields on assignment user = User(id=1, name="John Doe", email="john.doe@example.com") user.email = "new.email@example.com" # This assignment will trigger validation
In this example, validate_default is set to False to avoid unnecessary validation during initialization, and validate_assignment is set to True to ensure that fields are validated when they are updated.
Pydantic's BaseSettings class is designed for managing application settings, supporting environment variable loading and type validation.
This helps in configuring applications for different environments (e.g., development, testing, production).
Consider this .env file:
database_url=db secret_key=sk debug=False
Example of using BaseSettings:
from pydantic_settings import BaseSettings class Settings(BaseSettings): database_url: str secret_key: str debug: bool = False class Config: env_file = ".env" settings = Settings() print(settings.model_dump()) # Output: # {'database_url': 'db', 'secret_key': 'sk', 'debug': False}
In this example, settings are loaded from environment variables, and the Config class specifies that variables can be loaded from a .env file.
For using BaseSettings you will need to install an additional package:
pip install pydantic-settings
Managing settings effectively involves a few best practices:
One common mistake when using Pydantic is misapplying type annotations, which can lead to validation errors or unexpected behavior.
Here are a few typical mistakes and their solutions:
Ignoring performance implications when using Pydantic can lead to slow applications, especially when dealing with large datasets or frequent model instantiations.
Here are some strategies to avoid performance bottlenecks:
Overcomplicating Pydantic models can make them difficult to maintain and understand.
Here are some tips to keep models simple and maintainable:
Dans ce guide, nous avons couvert diverses bonnes pratiques pour utiliser efficacement Pydantic dans vos projets Python.
Nous avons commencé par les bases de démarrage avec Pydantic, y compris l'installation, l'utilisation de base et la définition de modèles. Nous avons ensuite exploré des fonctionnalités avancées telles que les types personnalisés, la sérialisation et la désérialisation, ainsi que la gestion des paramètres.
Des considérations clés en matière de performances, telles que l'optimisation de l'initialisation du modèle et l'analyse efficace des données, ont été mises en évidence pour garantir le bon fonctionnement de vos applications.
Nous avons également discuté des pièges courants, tels que l'utilisation abusive des annotations de type, l'ignorance des implications en termes de performances et la complexité excessive des modèles, et avons proposé des stratégies pour les éviter.
L'application de ces bonnes pratiques dans vos projets réels vous aidera à exploiter toute la puissance de Pydantic, rendant votre code plus robuste, maintenable et performant.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!