python - SQLAlchemy 覆盖 ==

标签 python sqlalchemy

我正在创建表示用户凭据的 SQLAlchemy 类。

我想要字段 password 存储密码的散列值。因此,我想通过以下方式覆盖它的行为:

  1. 当分配 credentials.password = value 时,它实际上存储值的散列

  2. 当比较 credentials.password == value 时,它实际上是与值的哈希值进行比较

我已阅读 SQLAlchemy 文档的以下部分 http://docs.sqlalchemy.org/en/rel_0_7/orm/mapper_config.html#using-descriptors-and-hybrids

而且我想我确实了解如何解决问题 1。

但是我不确定,如何做第二点。有没有一种安全的方法(不破坏 SQLAlchemy)?

这是示例模型:

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)

最佳答案

为了进行比较,由于您无法取消哈希密码,因此您需要为 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)    

关于python - SQLAlchemy 覆盖 ==,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12212636/

相关文章:

python - 服务器脱机时如何保持代码在客户端上运行

java - Python 中的 Servlet 等价物?

python - 属性错误: module 'sqlalchemy.util' has no attribute 'deprecated_params'

python - Sqlalchemy postgresql JSON 类型字段中的 null 和 None 转换

flask - SQLalchemy:多表一模式,启动时动态创建表

python - 使用 django.contrib.gis.measure.D 时出现 GeoDjango dwithin 错误

python - 自动在 Azure ML Studio Designer 中注册自定义模型并在设计器内部署

python - 将变量传递给正则表达式提取 Pandas

python - SQLAlchemy 0.7.8 原始字符串查询参数问题

python - 为 mariadb 和 postgres 数据库启用 ssl 是否会导致服务器过载或影响性能?