Software testing | Detailed explanation of using Pydantic BaseModel

Insert image description here

Introduction

When we write applications in Python, we often need to process and validate data. Pydanticis a popular library that helps us define data models and automate data validation. In Pydantic, BaseModelis a core concept that is used to define data models and validate input data. In this article, we will detail how to use Pydantic BaseModelto create and validate data models.

Why use BaseModel?

Pydantic is a Python library for data validation and parsing. It allows you to define data models and then use these models to validate and parse input data. A key feature of Pydantic is its type hints, which make code clearer and easier to understand.

In Pydanticis BaseModelan abstract base class used to define the data model. It provides a simple and powerful way to describe the structure of data and verify the validity of data. Using it BaseModelcan help us reduce the writing of manual verification code and improve the maintainability of the code.

Create a simple BaseModel

Let's start with a simple example, assuming we are developing an application that needs to handle users' personal information. We can BaseModeldefine a user data model using:

from pydantic import BaseModel

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

In this example, we define a named User, BaseModelwhich has three fields: username, emailand age, representing the user's username, email address, and age respectively. Type hints following the fields are required and Pydanticare used to validate the type of the input data.

Validate data using BaseModel

Once we define the User model, we can use it to validate data. Assuming we already have some user-provided data, we can pass this data as a dictionary to Userthe class constructor, which Pydanticwill automatically validate the data and create a User object:

user_data = {
    
    
    "username": "john_doe",
    "email": "[email protected]",
    "age": 30
}

user = User(**user_data)
print(user)

-------------
输出结果如下:
username='john_doe' email='[email protected]' age=30

ValidationErrorPydantic will raise an exception if the provided data does not match the model . We can catch this exception and handle validation errors tryusing :except

from pydantic import ValidationError

user_data = {
    
    
    "username": "john_doe",
    "email": ["invalid_email"],
    "age": "30"
}

try:
    user = User(**user_data)
except ValidationError as e:
    print(e)

In this example, the mailbox has the wrong data type, so Pydantic raises one ValidationError.

Use default values ​​and optional fields

Sometimes, some fields may be optional or we want to provide default values ​​for fields. In Pydantic, we can use Fieldclasses to implement these functions:

from pydantic import BaseModel, Field

class User(BaseModel):
    username: str = Field(..., min_length=3)
    email: str
    age: int = Field(default=18, ge=0)

In this example, usernamethe field is required and must contain at least 3 characters, emailthe field is optional, and agethe field has a default value of 18 and must be greater than or equal to 0.

Use nested models

In practical applications, we may need to define complex data models, including nested models. Of course Pydanticthe definition and validation of nested models is supported:

from pydantic import BaseModel

class Address(BaseModel):
    street: str
    city: str
    zip_code: str

class User(BaseModel):
    username: str
    email: str
    age: int
    address: Address

In this example, Userthe model contains a nested Addressmodel. We can use models as usual Userto validate data, including nested data:

user_data = {
    
    
    "username": "Muller",
    "email": "[email protected]",
    "age": 30,
    "address": {
    
    
        "street": "nanjing road",
        "city": "Shanghai",
        "zip_code": "10001"
    }
}
user = User(**user_data)
print(user)

-----------------
输出如下:
username='Muller' email='[email protected]' age=30 address=Address(street='nanjing road', city='Shanghai', zip_code='10001')

Summarize

Pydanticprovides BaseModela powerful tool for defining and validating data models. By using it BaseModel, we can reduce the workload of manually validating data and improve the readability and maintainability of the code. I hope this article can help you better understand how to use Pydanticto BaseModelcreate and validate data models.

Guess you like

Origin blog.csdn.net/Tester_muller/article/details/132908057