You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
User inherits from UserBase, I have tried not to define the attributes in User in different ways (with pydanitc and without pydantic) but it forces me to redefine the attributes in User even though they already exist in UserBase
fromtypingimportAny, ClassVar, Optionalfromflask_loginimportUserMixinfrommotor.motor_asyncioimportAsyncIOMotorCollectionfromodmanticimportAIOEngine, Field, Modelfromodmantic.modelimport_BaseODMModelfrompydanticimport (
BaseModel,
EmailStr,
SecretBytes,
SecretStr,
ValidationError,
field_serializer,
)
fromwerkzeug.securityimportcheck_password_hash, generate_password_hashclassUserBase(BaseModel, UserMixin):
email: EmailStrpassword: SecretStr_engine: ClassVar[AIOEngine]
model_config= {"arbitrary_types_allowed": True}
@classmethoddef_collection(cls) ->AsyncIOMotorCollection:
"""Obtiene la colección asociada."""ifnothasattr(cls, "_engine") ornotcls._engine:
raiseValueError("Cada subclase debe definir un engine.")
returncls._engine.get_collection(cls) # type: ignoredefget_id(self):
"""The return of this method is stored in the session and use in the user_loader from flask_login"""returnself.email#! ------------ EXTRA FIELDS -------------------------# projects: list[Project] = Field(default_factory=list)@field_serializer("password")defdump_secret_password(self, v: SecretStr) ->str:
"""User for serializer the password when uses _engine.save()"""returnv.get_secret_value()
def_encrypt_password(self) ->None:
secret_pw=self.password.get_secret_value()
self.password=generate_password_hash(secret_pw) # type: ignoredef_check_password(self, password: str) ->bool:
returncheck_password_hash(
pwhash=self.password.get_secret_value(),
password=password,
)
@classmethodasyncdefcreate_user(cls, email: str, password: str):
collection=cls._collection()
_user=awaitcollection.find_one(
{"email": email},
)
if_user:
raiseValueError("User already exists")
_new_user=cls(email=email, password=password)
_new_user._encrypt_password()
_stored_user=awaitcls._engine.save(_new_user)
if_stored_user:
returnstr(_stored_user.id)
raiseValueError("User not created")
@classmethodasyncdeflogin_user(cls, email: str, password: str) ->"UserBase":
user=awaitcls._engine.find_one(cls, cls.email==email)
ifuseranduser._check_password(password):
returnuserraiseValueError("User not found or password incorrect")
How does inheritance work with ODMantic models?
User inherits from UserBase, I have tried not to define the attributes in User in different ways (with pydanitc and without pydantic) but it forces me to redefine the attributes in User even though they already exist in UserBase
if comments
The text was updated successfully, but these errors were encountered: