目前这是不可能SecretStr
的。在提交 PR 之前,您可以使用验证器来实现相同的行为:
import re
from pydantic import AnyStrMinLengthError, AnyStrMaxLengthError, BaseModel, SecretStr, StrRegexError, validator
class SimpleModel(BaseModel):
password: SecretStr
@validator('password')
def has_min_length(cls, v):
min_length = 8
if len(v.get_secret_value()) < min_length:
raise AnyStrMinLengthError(limit_value=min_length)
return v
@validator('password')
def has_max_length(cls, v):
max_length = 32
if len(v.get_secret_value()) > max_length:
raise AnyStrMaxLengthError(limit_value=max_length)
return v
@validator('password')
def matches_regex(cls, v):
regex = r'.*\W'
if not re.match(regex, v.get_secret_value()):
raise StrRegexError(pattern=regex)
return v