简体   繁体   中英

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

Currently I have schema with field "name". I use constr to specify it

from pydantic import BaseModel, constr

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

I want to use pydantic StrictStr type like this:

from pydantic import BaseModel, StrictStr, Field

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

But it raises error:

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

In docs, as i understand, it advices to use use raw attribute name like maxLength isntead of max_length (like exclusiveMaximum for int) but this constraints are not enforced so validations are not applied.

My question is: How I can use StrictStr type for name field and apply native validations like min_length , max_length ?

You have multiple options here, either you create a new type based on StrictString, or you inherit from StrictString or you use constr with strict set to True. Creating a type as done below does the same as inheriting from StrictString, just a different syntax if you want. That should all give you the necessary type validations. In code, that would read like

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM