[Python] Pydantic validator and Fastapi validator use function introduction

validatoris 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 validatorthe 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 Usermodel with twousername attributes, and . passwordBy using validatorthe decorator , we add custom validation logic to these two properties, namely:

  • username_must_contain_letters: The value of the validation usernameattribute 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 logic usernamewill convert the value of to capitalized format.
  • password_min_length: Validation The value length of the passwordattribute 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;

validatorRefers 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.

validatorIt 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 validatorusing :

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 Querythe function to verify qwhether the request parameter complies with the defined rules. Among them, min_lengththe and max_lengthparameter are used to limit the length of the parameter, regexand the parameter is used to limit the format of the parameter.

Thus, /items/?q=fixedquerywhen , the following results are returned:

{
    
    
    "items": [
        {
    
    "item_id": "Foo"},
        {
    
    "item_id": "Bar"}
    ],
    "q": "fixedquery"
}

The /items/?q=queryrequest 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, validatordetailed error information will be returned to help developers quickly locate the problem.

Guess you like

Origin blog.csdn.net/qq_41604569/article/details/129960520