validator
is a decorator provided in the Pydantic module to add custom validation logic to attributes in the model. When we need to perform specific validation or conversion on the value of an attribute, we can use validator
the decorator to achieve it.
Here is a simple usage example:
from pydantic import BaseModel, validator
class User(BaseModel):
username: str
password: str
@validator('username')
def username_must_contain_letters(cls, v):
assert any(char.isalpha() for char in v), 'Username must contain letters'
return v.title()
@validator('password')
def password_min_length(cls, v):
assert len(v) >= 8, 'Password must be at least 8 characters long'
return v
In this example, we define a User
model with twousername
attributes, and . password
By using validator
the decorator , we add custom validation logic to these two properties, namely:
username_must_contain_letters
: The value of the validationusername
attribute must contain at least one letter. If the condition is not met, an exception will be thrown and an error message will be prompted. At the same time, this validation logicusername
will convert the value of to capitalized format.password_min_length
: Validation The value length of thepassword
attribute must be greater than or equal to 8. If the condition is not met, an exception will be thrown and an error message will be prompted.
In actual use, we can add multiple custom validation logics as needed. When the attributes of the model are changed, Pydantic will automatically execute the corresponding validation logic to ensure the validity of the model data.
The following part is related to the above, but not very close;
validator
Refers to the function or class used when validating input data. In FastAPI, you can use the validators provided by the Pydantic module to define data models and validate input data. Validators ensure that input data is of the correct type and format, automatically converting data types when necessary. This can effectively reduce the workload of developers and improve the reliability and robustness of applications. For example, a validator can be used to verify that a string is a valid email address or URL, or to verify that a number is within a specified range.
validator
It is a tool used in the FastAPI framework to verify request parameters. It can be used to check whether the request parameters conform to the defined rules, thereby avoiding some common request parameter errors.
Here is an example code validator
using :
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(q: str = Query(None, min_length=3, max_length=50, regex="^fixedquery$")):
results = {
"items": [{
"item_id": "Foo"}, {
"item_id": "Bar"}]}
if q:
results.update({
"q": q})
return results
In the above code, we define a GET request route /items/
, and use Query
the function to verify q
whether the request parameter complies with the defined rules. Among them, min_length
the and max_length
parameter are used to limit the length of the parameter, regex
and the parameter is used to limit the format of the parameter.
Thus, /items/?q=fixedquery
when , the following results are returned:
{
"items": [
{
"item_id": "Foo"},
{
"item_id": "Bar"}
],
"q": "fixedquery"
}
The /items/?q=query
request returns the following error message:
{
"detail": [
{
"loc": [
"query",
"q"
],
"msg": "ensure this value has at least 3 characters",
"type": "value_error.any_str.min_length",
"ctx": {
"limit_value": 3
}
},
{
"loc": [
"query",
"q"
],
"msg": "string does not match regex '^fixedquery$'",
"type": "value_error",
"ctx": {
"pattern": "^fixedquery$"
}
}
]
}
It can be seen that when the request parameters do not comply with the rules, validator
detailed error information will be returned to help developers quickly locate the problem.