2016-11-27 14 views
0

私は以下のようなモデルを持っています。私がしようとしているのは、.filter_by(api_key=$key)を実行する固有の能力を提供することです。これは私が収集できるすべてのものから、コンパレータの使用を必要とします。それは、私はかなりそこに着くことができなかったと言いました。SQLAlchemy Hybrid Property Comparator

私が後だものをコンパレータで、もしそうなら、私はこのケースで間違って何をやっていますか?

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') 

答えて

0

判読が難しいことが分かります。 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) 
関連する問題