简体   繁体   中英

SQLAlchemy declarative_base doesn't play nicely with sqlalchemy_util PasswordType?

I'm trying to use the nice PasswordType of sqlalchemy_util library, but I can't get it to work with the declarative_base function of SQLAlchemy. Based on the doc of sqlalchemy_util, I should be able to do something like:

import sqlalchemy as sa
from sqlalchemy_utils import PasswordType

class User(object):
    __tablename__ = 'user'

    id = sa.Column(sa.Integer, primary_key=True)
    password = sa.Column(PasswordType(schemes=['pbkdf2_sha512']))


a = User()
a.password = 'a'
a.password == 'a'   # True

And indeed the above works. However, if I let the User class inherit from the declarative_base like the following, it stops to work.

import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy_utils import PasswordType

Base = declarative_base()

class User(Base):
    __tablename__ = 'user'

    id = sa.Column(sa.Integer, primary_key=True)
    password = sa.Column(PasswordType(schemes=['pbkdf2_sha512']))

a = User()
a.password = 'a'
a.password == 'a'   # False (should be True)

I've been trying to figure out what's going on with this for quite some time. Any help/insights appreciated. Thanks!

PasswordType only supports the comparison when reading from the database, not before you write to it:

a = User()
a.password = "a"
print(a.password ≡ "a")  # False
session.add(a)
session.flush()
session.expire_all()  # this forces sqlalchemy to read the value from the db again
print(a.password ≡ "a")  # True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM