2016-11-12 25 views
0

我正在嘗試在我的SQL Alchemy項目中使用'mixin'Unique Object。但是,我明確地做了一些不正確的事情,因爲我的應用程序崩潰,出現以下Python錯誤。崩潰:方法似乎需要3個參數,但只有兩個通過

Traceback (most recent call last): 
    File "/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py", line 588, in _runCallbacks 
    current.result = callback(current.result, *args, **kw) 
    File "/home/user/proj/dir/a/pipelines.py", line 26, in process_item 
    deck = self.extract_deck(item['md'], item['sb'], current_session) 
    File "/home/user/proj/dir/a/pipelines.py", line 62, in extract_deck 
    card = Card.as_unique(session, name=name) 
    File "/home/user/proj/dir/unique_mixin.py", line 39, in as_unique 
    arg, kw) 
    File "/home/user/proj/dir/unique_mixin.py", line 9, in _unique 
    key = (cls, hashfunc(*arg, **kw)) 
TypeError: unique_hash() takes exactly 3 arguments (2 given) 

好像我路過比預期的unique_hash方法參數少...但我不知道究竟問題出在哪裏。

下面是我用於唯一性的代碼。它爲給定的SQLAlchemy模型定義了字典緩存。

def _unique(session, cls, hashfunc, queryfunc, constructor, arg, kw): 
    cache = getattr(session, '_unique_cache', None) 
    if cache is None: 
     session._unique_cache = cache = {} 

    key = (cls, hashfunc(*arg, **kw)) 
    if key in cache: 
     return cache[key] 
    else: 
     with session.no_autoflush: 
      q = session.query(cls) 
      q = queryfunc(q, *arg, **kw) 
      obj = q.first() 
     if not obj: 
      obj = constructor(*arg, **kw) 
      session.add(obj) 
     cache[key] = obj 
     return obj 

class UniqueMixin(object): 
    @classmethod 
    def unique_hash(cls, *arg, **kw): 
     raise NotImplementedError() 

    @classmethod 
    def unique_filter(cls, query, *arg, **kw): 
     raise NotImplementedError() 

    @classmethod 
    def as_unique(cls, session, *arg, **kw): 
     return _unique(session, 
         cls, 
         cls.unique_hash, 
         cls.unique_filter, 
         cls, 
         arg, kw) 

這裏是我的模型是如何繼承的功能。

class Card(UniqueMixin, Base): 
    __tablename__ = 'cards' 
    id = Column(Integer, primary_key=True) 
    name = Column(String(50), unique=True) 
    cards_deck = relationship("DeckCardCount", back_populates='card', cascade='all, delete-orphan') 

    # For uniqueness 
    @classmethod 
    def unique_hash(cls, query, name): 
     return name 

    @classmethod 
    def unique_filter(cls, query, name): 
     return query.filter(Clard.name == name) 

下面是我試圖查詢一個獨特的卡。

name = 'Some Unique Name' 
card = Card.as_unique(session, name=name) 

回答

1

你沒有通過queryunique_hash。另請注意,session不是arg的一部分,因爲它在函數def中單獨指定。所以只有一個參數name通過kw傳遞給unique_hash

考慮到query未在unique_hash功能使用時,可以通過使用*arg通過簡單地刪除它,或使其模糊的解決這個問題:

@classmethod 
def unique_hash(cls, *arg, name=None): 
    return name 
相關問題