SQL Alchemy Overrides ==

I am creating an SQLAlchemy class that represents user credentials.

I want to have a field passwordthat stores the hashed password value. Therefore, I would like to redefine its behavior as follows:

  • When assigned, credentials.password = valueit actually stores a hash of value

  • When comparing, credentials.password == valueit actually compares with the hash of the value

I read the next part of the SQLAlchemy documentation http://docs.sqlalchemy.org/en/rel_0_7/orm/mapper_config.html#using-descriptors-and-hybrids

And I think I understand how to solve problem number 1.

However, I am not sure how to make the second point. Is there a way to do this in a safe way (without breaking SQLAlchemy)?

Here is an example of a model:

class Credentials(Base):
    __tablename__ = 'credentials'

    id = Column(Integer, primary_key=True)

    _password = Column('password', String)

    @hybrid_property
    def password(self):
        return self._password

    @password.setter(self):
        self._password = hash(self._password)
+3
1

, , Column, eq:

class MyPasswordType(String):
    class comparator_factory(String.Comparator):
        def __eq__(self, other):
            return self.operate(operators.eq, hash(other))

: http://docs.sqlalchemy.org/en/latest/core/types.html#types-operators

http://docs.sqlalchemy.org/en/latest/core/types.html#sqlalchemy.types.TypeEngine.comparator_factory

, :

@password.setter
def password(self, value):
    self._password = hash(value)    
+2

All Articles