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)