pydantic无法区分整数和字符串

Myu*_*Hun 5 python validation marshmallow pydantic

from pydantic import BaseModel


class AuthenticationResponseSchema(BaseModel):
    type: str
Run Code Online (Sandbox Code Playgroud)
schema = AuthenticationResponseSchema(type=1)
Run Code Online (Sandbox Code Playgroud)

现在我正在将 marshmallow 更改为 pydantic 的架构、模型......

type但 pydantic 模式在数据响应时未进行验证。

的数据类型type是字符串,但也传递了整数。

怎么了?

谢谢。

Tom*_*cik 13

正如文档中的 statad 所示

字符串按原样接受,int float 和 Decimal 使用 str(v) 强制转换,bytes 和 bytearray 使用 v.decode() 转换,从 str 继承的枚举使用 v.value 转换,所有其他类型都会导致错误

如果你想强制字符串,有一个叫做 的东西Strict Types,所以你可以使用StrictStr.

from pydantic import BaseModel, StrictStr


class AuthenticationResponseSchema(BaseModel):
    type: StrictStr


schema = AuthenticationResponseSchema(type=1)

Run Code Online (Sandbox Code Playgroud)

  • 这似乎违反了强类型精神和最小惊喜原则 - 我不喜欢这个设计决定 (10认同)