在 Pydantic v2 中定义带有约束的 Annotated[str]

问题描述 投票:0回答:1

假设我想要一个可以在整个应用程序中重复使用的校验和验证器。 Python 类型提示系统在 3.9+ 中发生了很大变化,这让我更加困惑。在 pydantic v1 中,我对

str
进行了子类化并实现了
__get_pydantic_core_schema__
__get_validators__
类方法。 v2 改变了其中的一些,首选方式已更改为使用带注释的类型。

pydantic-extra-types 包中,我找到了需要深入了解 pydantic 内部工作原理的示例。我可以复制并让某些东西起作用,但我更愿意找到“正确”的用户方法来完成它,而不是在不理解的情况下进行复制。

在 pydantic v2 中,看起来我可以将约束字符串作为 pydantic 类的一部分,例如

from typing import Annotated
from pydantic import BaseModel, StringConstraints

class GeneralThing(BaseModel):
  special_string = Annotated[str, StringConstraints(pattern="^[a-fA-F0-9]{64}$")]

但这无效(pydantic.errors.PydanticUserError:检测到未注释的属性)。此外,我必须注释我想要限制的每个字段,而不是我过去能够做的

special_string = ChecksumStr

python-3.x type-hinting pydantic
1个回答
0
投票

对于 pydantic,您需要 注释 您的字段,但您正在分配它们。 下面的代码应该可以满足你的需要

from typing import Annotated
from pydantic import BaseModel, StringConstraints

ChecksumString = Annotated[str, StringConstraints(pattern="^[a-fA-F0-9]{64}$")]

class GeneralThing(BaseModel):
  special_string: ChecksumString 

注意是

special_string: ChecksumString
而不是
special_string = ChecksumString
special_string: Annotated[str, StringConstraints(...)
仅仅知道也是有效的。

© www.soinside.com 2019 - 2024. All rights reserved.