如何在像 StrictStr 这样的严格类型的 Pydantic 中使用验证器?

How to use validators in Strict Types of Pydantic like StrictStr?

目前我有包含字段“名称”的模式。我用constr来指定

from pydantic import BaseModel, constr

class MySchema(BaseModel):
    name: constr(strict=True, min_length=1, max_length=50)

我想像这样使用 pydantic StrictStr 类型:

from pydantic import BaseModel, StrictStr, Field

class MySchema(BaseModel):
    name: StrictStr = Field(min_length=1, max_length=50)

但它引发错误:

E   ValueError: On field "name" the following field constraints are set but not enforced: max_length, min_length.
E   For more details see https://pydantic-docs.helpmanual.io/usage/schema/#unenforced-field-constraints

在文档中,据我所知,它建议使用 maxLength 之类的原始属性名称而不是 max_length(例如 exclusiveMaximum 用于 int),但不会强制执行此约束未应用验证。

我的问题是:如何为名称字段使用 StrictStr 类型并应用 min_lengthmax_length?

等本机验证

这里有多种选择,您可以创建一个基于 StrictString 的新类型,或者继承自 StrictString,或者使用 constr 并将 strict 设置为 True。如下所示创建类型与从 StrictString 继承相同,只是语法不同而已。这应该都给你必要的类型验证。在代码中,读起来像

MyStrictStr1 = type('MyStrictStr', (StrictStr,), {"min_length":1, "max_length":5})


class MyStrictStr2(StrictStr):
    min_length = 1
    max_length = 5

MyStrictStr3 = constr(min_length=1, max_length=5, strict=True)