目前我有欄位“名稱”的模式。我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
據我了解,在檔案中,它建議使用原始屬性名稱,例如maxLengthistead of max_length(like exclusiveMaximumfor int),但不強制執行此約束,因此不應用驗證。
我的問題是:如何將StrictStr型別用于名稱欄位并應用本機驗證min_length,例如max_length?
uj5u.com熱心網友回復:
這里有多種選擇,要么基于 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/425410.html
標籤:Python python-3.x 形式 验证 书呆子的
