在 Pydantic 中,如何将我在基本模型中设置的标志应用到我的自定义类型?
In Pydantic, how do I apply the flags that I have set in my base model to my custom type?
在我的模型中,我有必填字段。用户尽量避免使用破折号 (-) 作为输入来填写这些字段。为了避免这种情况发生,我在 Pydantic 中编写了一个自定义字符串类型。自定义类型检查输入是否应更改为 None 并检查是否允许为 None。我遇到的问题是我的自定义类型不使用我的 BaseModel 的标志。如anystr_strip_whitespace,去掉字符串首尾的空格。我希望 BaseModel 的配置也应用于我的自定义类型。因此,我希望任何人都可以帮助我解决有关在自定义类型中应用 BaseModel 标志的问题。
感谢所有帮助
一些示例代码:
class MyBaseModel(BaseModel):
class Config:
anystr_strip_whitespace = True
class EmptyStrToNone(str):
@classmethod
def __get_validators__(cls):
yield cls.change_empty_string_to_none
@classmethod
def change_empty_string_to_none(cls, value: str, field: ModelField) -> Optional[str]:
"""If the field is Optional, the input which represents an empty string is set to None.
If the field is required, instead of returning None it raises an Exception."""
is_required = field.required
lowercase_value = str(value).lower()
if is_required:
# Faulty cases that raise an exception
# E.g. check in a dictionary if it has a string such as "not specified" that represents an empty string.
elif # Optional condition
return None
return str_validator(value)
您可以收到 config
并用它来决定是否应该删除 str
。来自 Validators - pydantic:
A few things to note on validators:
[...]
you can also add any subset of the following arguments to the signature (the names must match):
- [...]
config
: the model config
完整示例:
from pydantic import BaseConfig, BaseModel
from pydantic.validators import str_validator
class MyStr(str):
@classmethod
def __get_validators__(cls):
yield str_validator
yield cls._strip_whitespace
# Yield more custom validators if needed
@classmethod
def _strip_whitespace(cls, value: str, config: BaseConfig) -> str:
if config.anystr_strip_whitespace:
return value.strip()
return value
class MyBaseModel(BaseModel):
my_str: MyStr
class Config:
anystr_strip_whitespace = True
print(MyBaseModel(my_str=" a "))
输出:
my_str='a'
在我的模型中,我有必填字段。用户尽量避免使用破折号 (-) 作为输入来填写这些字段。为了避免这种情况发生,我在 Pydantic 中编写了一个自定义字符串类型。自定义类型检查输入是否应更改为 None 并检查是否允许为 None。我遇到的问题是我的自定义类型不使用我的 BaseModel 的标志。如anystr_strip_whitespace,去掉字符串首尾的空格。我希望 BaseModel 的配置也应用于我的自定义类型。因此,我希望任何人都可以帮助我解决有关在自定义类型中应用 BaseModel 标志的问题。
感谢所有帮助
一些示例代码:
class MyBaseModel(BaseModel):
class Config:
anystr_strip_whitespace = True
class EmptyStrToNone(str):
@classmethod
def __get_validators__(cls):
yield cls.change_empty_string_to_none
@classmethod
def change_empty_string_to_none(cls, value: str, field: ModelField) -> Optional[str]:
"""If the field is Optional, the input which represents an empty string is set to None.
If the field is required, instead of returning None it raises an Exception."""
is_required = field.required
lowercase_value = str(value).lower()
if is_required:
# Faulty cases that raise an exception
# E.g. check in a dictionary if it has a string such as "not specified" that represents an empty string.
elif # Optional condition
return None
return str_validator(value)
您可以收到 config
并用它来决定是否应该删除 str
。来自 Validators - pydantic:
A few things to note on validators:
[...]
you can also add any subset of the following arguments to the signature (the names must match):
- [...]
config
: the model config
完整示例:
from pydantic import BaseConfig, BaseModel
from pydantic.validators import str_validator
class MyStr(str):
@classmethod
def __get_validators__(cls):
yield str_validator
yield cls._strip_whitespace
# Yield more custom validators if needed
@classmethod
def _strip_whitespace(cls, value: str, config: BaseConfig) -> str:
if config.anystr_strip_whitespace:
return value.strip()
return value
class MyBaseModel(BaseModel):
my_str: MyStr
class Config:
anystr_strip_whitespace = True
print(MyBaseModel(my_str=" a "))
输出:
my_str='a'