gpt4 book ai didi

python - Pydantic:如果没有传递,如何将默认值传递给变量?

转载 作者:行者123 更新时间:2023-12-03 17:43:38 28 4
gpt4 key购买 nike

如果在字段中传递 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 模型中工作:
尝试实现 getter 和 setter:
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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com