作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如果在字段中传递 None ,我可以在 Pydantic 中设置默认值吗?
我有以下代码,但在我看来,这里的验证器仅适用于模型的初始化,而不适用于其他情况。
我的代码:
class User(BaseModel):
name: Optional[str] = ''
password: Optional[str] = ''
email: EmailStr
@validator('name')
def set_name(cls, name):
return name or 'foo'
遇到的问题:
user = User(name=None, password='some_password', email='user@example.com')
print("Name is ", user.name)
# > 'Name is foo'
user.name = None
print("Name is ", user.name)
# > 'Name is None'
所需输出:
user = User(name='some_name', password='some_password', email='user@example.com')
user.name = None
print("Name is ", user.name)
# > 'Name is foo'
关于如何获得所需输出的任何想法?我认为拥有 getter 和 setter 将有助于解决这个问题。但是,我无法让它们在 Pydantic 模型中工作:
class User(BaseModel):
name: Optional[str] = ''
password: Optional[str] = ''
email: EmailStr
def get_password(self):
return self.password
def set_password(self, password):
self.password = hash_password(password)
password = property(get_password, set_password)
user = User(name='some_name', password='some_password', email='user@example.com')
# > RecursionError: maximum recursion depth exceeded
我还尝试了属性装饰器:
class User(BaseModel):
name: Optional[str] = ''
password: Optional[str] = ''
email: EmailStr
@property
def password(self):
return self._password
@password.setter
def password(self, password):
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
self._password = pwd_context.hash(password)
user = User(name='some_name', email='user@example.com')
user.password = 'some_password'
# > ValueError: "User" object has no field "password"
我也尝试覆盖 初始化 :
class User(BaseModel):
name: Optional[str] = ""
password: Optional[str] = ""
email: EmailStr
def __init__(self, name, password, email):
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
password = pwd_context.hash(password)
super().__init__(name=name, password=password, email=email)
user = User(name="some_name", password="some_password", email='user@example.com')
print(user.password)
# > AYylwSnbQgCHrl4uue6kO7yiuT20lazSzK7x # Works as expected
user.password = "some_other_password"
print(user.password)
# > "some_other_password" # Does not work
user.password = None
print(user.password)
# > None # Does not work either
最佳答案
您需要启用 validate_assignment
模型配置中的选项:
from typing import Optional
from pydantic import BaseModel, validator
class User(BaseModel):
name: Optional[str] = ''
password: Optional[str] = ''
class Config:
validate_assignment = True
@validator('name')
def set_name(cls, name):
return name or 'foo'
user = User(name=None, password='some_password', )
print("Name is ", user.name)
user.name = None
print("Name is ", user.name)
Name is foo
Name is foo
关于python - Pydantic:如果没有传递,如何将默认值传递给变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63616798/
我是一名优秀的程序员,十分优秀!