其他分享
首页 > 其他分享> > pydantic模型配置

pydantic模型配置

作者:互联网

1.配置参数

2.配置方式

2.1模型配置
from pydantic import BaseModel, ValidationError


class Model(BaseModel):
    v: str

    class Config:
        max_anystr_length = 10
        error_msg_templates = {
            'value_error.any_str.max_length': 'max_length:{limit_value}',
        }


try:
    Model(v='x' * 20)
except ValidationError as e:
    print(e)
    """
    1 validation error for Model
    v
      max_length:10 (type=value_error.any_str.max_length; limit_value=10)
    """
2.2通过kwargs进行传参
from pydantic import BaseModel, ValidationError, Extra


class Model(BaseModel, extra=Extra.forbid):
    a: str


try:
    Model(a='spam', b='oh no')
except ValidationError as e:
    print(e)
    """
    1 validation error for Model
    b
      extra fields not permitted (type=value_error.extra)
    """
2.3使用类装饰器
from datetime import datetime

from pydantic import ValidationError
from pydantic.dataclasses import dataclass


class MyConfig:
    max_anystr_length = 10
    validate_assignment = True
    error_msg_templates = {
        'value_error.any_str.max_length': 'max_length:{limit_value}',
    }


@dataclass(config=MyConfig)
class User:
    id: int
    name: str = 'John Doe'
    signup_ts: datetime = None


user = User(id='42', signup_ts='2032-06-21T12:00')
try:
    user.name = 'x' * 20
except ValidationError as e:
    print(e)
    """
    1 validation error for User
    name
      max_length:10 (type=value_error.any_str.max_length; limit_value=10)
    """

3.全局生效配置

from pydantic import BaseModel as PydanticBaseModel


class BaseModel(PydanticBaseModel):
    class Config:
        arbitrary_types_allowed = True


class MyClass:
    """A random class"""


class Model(BaseModel):
    x: MyClass

4.别名生成器

from pydantic import BaseModel


def to_camel(string: str) -> str:
    return ''.join(word.capitalize() for word in string.split('_'))


class Voice(BaseModel):
    name: str
    language_code: str

    class Config:
        alias_generator = to_camel


voice = Voice(Name='Filiz', LanguageCode='tr-TR')
print(voice.dict())  # {'name': 'Filiz', 'language_code': 'tr-TR'}
print(voice.dict(by_alias=True))  # {'Name': 'Filiz', 'LanguageCode': 'tr-TR'}

5.别名优先级

1.直接在模型上Field(..., alias=)
2.直接在模型上Config.fields fields = {'language_code': 'lang'}
3.在父模型上Field(..., alias=)
4.父模型上定义在 中定义Config.fields
6.无论它是在模型上还是在父模型上alias_generator

6.Smart Union

from typing import Union

from pydantic import BaseModel


class Foo(BaseModel):
    pass


class Bar(BaseModel):
    pass


class Model(BaseModel):
    x: Union[str, int]
    y: Union[Foo, Bar]


print(Model(x=1, y=Bar()))
# x='1' y=Foo()
from typing import Union

from pydantic import BaseModel


class Foo(BaseModel):
    pass


class Bar(BaseModel):
    pass


class Model(BaseModel):
    x: Union[str, int]
    y: Union[Foo, Bar]

    class Config:
        smart_union = True


print(Model(x=1, y=Bar()))
# x=1 y=Bar()
from typing import List, Union

from pydantic import BaseModel


class Model(BaseModel, smart_union=True):
    x: Union[List[str], List[int]]


# Expected coercion
print(Model(x=[1, '2']))
# x=['1', '2']

# Unexpected coercion
print(Model(x=[1, 2]))
# x=['1', '2']

标签:模型,配置,length,str,BaseModel,import,Model,class,pydantic
来源: https://www.cnblogs.com/puffer/p/16380714.html