Introduction
When we write applications in Python, we often need to process and validate data. Pydantic
is a popular library that helps us define data models and automate data validation. In Pydantic
, BaseModel
is a core concept that is used to define data models and validate input data. In this article, we will detail how to use Pydantic BaseModel
to 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 Pydantic
is BaseModel
an 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 BaseModel
can 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 BaseModel
define 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
, BaseModel
which has three fields: username
, email
and age
, representing the user's username, email address, and age respectively. Type hints following the fields are required and Pydantic
are 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 User
the class constructor, which Pydantic
will 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
ValidationError
Pydantic will raise an exception if the provided data does not match the model . We can catch this exception and handle validation errors try
using :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 Field
classes 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, username
the field is required and must contain at least 3 characters, email
the field is optional, and age
the 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 Pydantic
the 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, User
the model contains a nested Address
model. We can use models as usual User
to 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
Pydantic
provides BaseModel
a 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 Pydantic
to BaseModel
create and validate data models.