python-2.7 - SQLAlchemy 混合属性比较器

标签 python-2.7 sqlalchemy

我有一个如下所述的模型。我试图做的是提供执行 .filter_by(api_key=$key) 的 native 功能,从我收集到的所有信息来看,这需要使用比较器。也就是说,我还没能完全做到这一点。

我想要的是比较器吗?如果是,在这种情况下我做错了什么?

class ApiKey(hs_base, HomestackDatabase):
"""
Class that represents our API Keys table
"""

__tablename__   = 'ApiKeys'

# int: API key id
api_key_id      = Column(INTEGER(unsigned=True), primary_key=True)

# int: User id for this key
user_id         = Column(INTEGER(unsigned=True), ForeignKey("Users.user_id"), nullable=False)

# bin: A UUID in binary format
_api_key        = Column('api_key', BINARY(16), unique=True, nullable=False, default=lambda: str(uuid4()).replace('-', '').decode('hex'))

# str: brief description for usage of this key
description     = Column(VARCHAR(255))

# datetime: The time the record was originally created
created         = Column(DATETIME, default=datetime.utcnow, nullable=False, index=True)

# object: Convienience relationship to our User class
user            = relationship("User")


class ApiKeyComparator(Comparator):
    """
    provides an __eq__() method that will run against both sides of the expression
    when we're trying to filter_by(api_key=something)
    """
    def __init__(self, api_key):
        self.api_key = api_key.replace('-', '').decode('hex')

    def __eq__(self, other):
        return self.api_key == other.replace('-', '').decode('hex')

@hybrid_property
def api_key(self):
    return str(UUID(self._api_key.encode("hex")))

@api_key.comparator
def api_key(cls):
    return ApiKey.ApiKeyComparator(cls._api_key)

@api_key.setter
def api_key(self, apikey):
    self._api_key = api_key.replace('-', '').decode('hex')

最佳答案

事实证明,读书很难。

ApiKey 类中,将 class ApiKeyComparator... 替换为以下内容。

class ApiKeyComparator(Comparator):
    """
    provides an __eq__() method that will run against both sides of the expression
    when we're trying to filter_by(api_key=something)
    http://docs.sqlalchemy.org/en/latest/orm/extensions/hybrid.html#building-custom-comparators
    """
    def __eq__(self, other):
        return self.__clause_element__() == other.replace('-', '').decode('hex')

@hybrid_property
def api_key(self):
    return str(UUID(self._api_key.encode("hex")))

@api_key.comparator
def api_key(cls):
    return ApiKey.ApiKeyComparator(cls._api_key)

关于python-2.7 - SQLAlchemy 混合属性比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40830176/

相关文章:

python - 查找类对象是否在数组/列表中

python - sqlalchemy.exc.ProgrammingError : (psycopg2. ProgrammingError) 无法适配类型 'property'

python - SQLAlchemy 过滤时出错

python - 如果 Flask 上不存在表,如何使用 SQLAlchemy 创建表?

python - 如何为每个 CSV 文件创建单独的 Pandas DataFrame 并给它们起有意义的名字?

python - 使用 self.sender() 检查 PyQt QPushButton 是否被检查

python - 如何在sqlalchemy中指定表的填充因子?

python - SQLAlchemy select_from 单个表

python - 使用类装饰器,如何在不重新定义类的情况下重写方法?

python - 如何从 python 中的复选按钮获取文本? (Tkinter)