instructor

Форк
0
/
field_validator.py 
42 строки · 1.2 Кб
1
from pydantic import BaseModel, ValidationError, field_validator
2

3

4
class UserDetail(BaseModel):
5
    age: int
6
    name: str
7

8
    @field_validator("name", mode="before")
9
    def name_must_contain_space(cls, v):
10
        """
11
        This validator will be called after the default validator,
12
        and will raise a validation error if the name does not contain a space.
13
        then it will set the name to be lower case
14
        """
15
        if " " not in v:
16
            raise ValueError("name be a first and last name separated by a space")
17
        return v.lower()
18

19

20
# Example 1) Valid input, notice that the name is lowercased
21
person = UserDetail(age=29, name="Jason Liu")
22
print(person.model_dump_json(indent=2))
23
"""
24
{
25
    "age": 29,
26
    "name": "jason liu"
27
}
28
"""
29

30
# Example 2) Invalid input, we'll get a validation error
31
# In the future this validation error will be raised by the API and
32
# used by the LLM to generate a better response
33
try:
34
    person = UserDetail(age=29, name="Jason")
35
except ValidationError as e:
36
    print(e)
37
    """
38
    1 validation error for UserDetail 
39
        name
40
    Value error, must contain a space [type=value_error, input_value='Jason', input_type=str]
41
        For further information visit https://errors.pydantic.dev/2.3/v/value_error
42
    """
43

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.