Software testing | Data validation using Pydantic Validator validator - detailed explanation of pre and each_item validators

Insert image description here

Preface

Pydantic is a powerful Python library for data validation and parsing. In Pydantic, a validator is a mechanism for performing custom validation logic on the properties of a data model. This article will focus on two validators in Pydantic: pre and each_item, and how to use them to validate the properties of the data model.

pre validator

The pre validator allows us to perform custom validation logic before assigning data to the property. For example, let's say we have a data model Personthat contains a name attribute, and we want to ensure that the name is not an empty string:

from pydantic import BaseModel, validator

class Person(BaseModel):
    name: str

    @validator('name', pre=True)
    def check_name_length(cls, name):
        if len(name) == 0:
            raise ValueError("名字不能为空字符串")
        return name

In this example, we define a validator named using @validatorthe decorator and parameters. It checks whether the name attribute is an empty string and, if so, raises a value error.pre=Truecheck_name_length

Now let's verify that this validator works:

try:
    person = Person(name="")
except ValueError as e:
    print(e)  # 输出:"名字不能为空字符串"

Running the script will output the following, and we will collect this verification error:

1 validation error for Person
name
  名字不能为空字符串 (type=value_error)

We can confirm that the pre validator we added took effect successfully and the custom validation logic was executed before the properties of the data model were set.

each_item validator

each_itemValidators are used to validate the value of each element in a collection type (such as a list, dictionary, etc.). For example, let's say we have a data model Productthat contains a price attribute, and we want to ensure that the prices are all greater than zero:

from pydantic import BaseModel, validator
from typing import List

class Product(BaseModel):
    prices: List[float]

    @validator('prices', each_item=True)
    def check_price(cls, price):
        if price <= 0:
            raise ValueError("价格必须大于零")
        return price

In this example, we each_item=Truedefine a check_pricevalidator named using the parameter. It checks prices if each price in the attribute is greater than zero, and if not, raises a value error.

Now, let's test this validator:

try:
    product = Product(prices=[10.0, -5.0, 20.0])
except ValueError as e:
    print(e)  # 输出:"价格必须大于零"

Running the script will output the following content:

1 validation error for Product
prices -> 1
  价格必须大于零 (type=value_error)

We can find that our each_itemvalidator takes effect successfully and executes custom validation logic for each element in the collection type.

Summarize

Pydantic's preand each_itemvalidators provide powerful tools for data validation, allowing us to perform custom validation logic before data model properties are set and before collection type elements are added. This makes data validation more flexible and controllable, helping to ensure applications accept and process valid data. By having a deep understanding of Pydantic's validator mechanism, we can better deal with various data validation needs and improve the robustness and maintainability of our code.

For more artificial intelligence learning materials, please click!

Guess you like

Origin blog.csdn.net/Tester_muller/article/details/132990226
Recommended