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
Pydantic
It 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.BaseModel
and 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 Person
model named with three fields: name
and age
and 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:
- 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']
- 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.ValidationError
an 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)
- 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)
- 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)
- Handle validation errors
When validation fails, Pydantic provides detailed error information so we can handle the error. We can pydantic.ValidationError
access 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.
- 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 @validator
define 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_positive
method that will verify that age is a positive integer.
Summarize
Pydantic
is 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 Pydantic
can help us process data more easily. Pydantic
I hope this article will be helpful for everyone to get started !