Software testing | Detailed introduction and basic introduction to Pydantic

Insert image description here

Introduction

Pydantic is a powerful Python library for data validation and parsing, specifically for working with JSON data. Its main goal is to make data validation and parsing simple, intuitive and maintainable. This article will introduce the basics of Pydantic, including how to define models, validate data, and handle errors.

What is Pydantic?

Pydantic is a library for data validation and parsing that allows us to define data models and validate input data against those models. One of its important features is that it automatically converts input data into strongly typed Python objects and provides clear error messages so that we can easily handle validation failures.

Install Pydantic

PydanticIt is a third-party library of Python. We can install it directly using the pip command. The command is as follows:

pip install pydantic

Define Pydantic model

To use Pydantic, you first need to define a model class. A model class is an ordinary Python class that inherits from pydantic.BaseModeland defines the data fields and their types. Here's a simple example:

from pydantic import BaseModel

class Person(BaseModel):
    name: str
    age: int
	hooby: list

In this example, we define a Personmodel named with three fields: nameand ageand hobby, with string, integer, and list types respectively. Pydantic will use these field definitions to validate input data.

Using Pydantic models

Once the Pydantic model is defined, we can use it to validate and parse data. Here are some common usage examples:

  1. Create model instance

We can create model instances by passing dictionary data, for example:

data = {
    
    "name": "Alice", "age": 30, "hobby": ['football']}
person = Person(**data)
print(person)

----------
#######
输出结果如下:
name='Alice' age=30 hobby=['football']
  1. data verification

Pydantic automatically verifies that the input data conforms to the model's definition. If the input data does not meet the definition, pydantic.ValidationErroran exception will be thrown. For example:

data = {
    
    "name": "Bob", "age": "thirty", "hobby": "basketball"}
person = Person(**data)  # 这里将引发ValidationError异常

----------
运行脚本,报错如下:
 person = Person(**data)  # 这里将引发ValidationError异常
  File "pydantic\main.py", line 331, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 2 validation errors for Person
age
  value is not a valid integer (type=type_error.integer)
hobby
  value is not a valid list (type=type_error.list)
  1. Get field value

We can access the value of a model field just like a normal class property:

data = {
    
    "name": "Muller", "age": 30, "hobby": ['football', 'reading', 'running']}
person = Person(**data)

print(person.name)
print(person.age)
print(person.hobby)
  1. Convert to dictionary

We can convert the model instance to a dictionary so that it can be serialized into JSON data:

data = {
    
    "name": "Muller", "age": 30, "hobby": ['football', 'reading', 'running']}
person = Person(**data)

person_dict = person.dict()
print(person_dict)
  1. Handle validation errors

When validation fails, Pydantic provides detailed error information so we can handle the error. We can pydantic.ValidationErroraccess error information by catching exceptions. Here is an example:

from pydantic import BaseModel
from pydantic import ValidationError

class Person(BaseModel):
    name: str
    age: int
    hobby: list


try:
    data = {
    
    "name": "Muller", "age": "thirty", "hobby": ['football', 'reading', 'running']}
    person = Person(**data)
except ValidationError as e:
    print(e)

-------------
运行脚本,结果如下:
1 validation error for Person
age
  value is not a valid integer (type=type_error.integer)

We can see that the output contains an error message with detailed information about the validation failure, which will help us quickly identify and solve the problem.

  1. Custom validation rules

In addition to basic type validation, we can also customize validation rules. For example, if we want to ensure that the age is within a specific range, we can @validatordefine a custom validation function using a decorator:

from pydantic import validator

class Person(BaseModel):
    name: str
    age: int
    hobby:list

    @validator("age")
    def age_must_be_positive(cls, age):
        if age < 0:
            raise ValueError("Age must be a positive integer")
        return age

In this example, we define a age_must_be_positivemethod that will verify that age is a positive integer.

Summarize

Pydanticis a powerful Python library for data validation and parsing. It enables you to easily define data models, validate data, handle errors, and customize validation rules. Whether you are building a web application, API, command line tool, or any other type of Python application, it Pydanticcan help us process data more easily. PydanticI hope this article will be helpful for everyone to get started !

Guess you like

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