[英]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
(如用於 int 的exclusiveMaximum
),但不強制執行此約束,因此不應用驗證。
我的問題是:如何將StrictStr
類型用於名稱字段並應用本機驗證,如min_length
、 max_length
?
這里有多種選擇,要么基於 StrictString 創建新類型,要么從 StrictString 繼承,或者使用將嚴格設置為 True 的 constr。 如下所示創建類型與從 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.