崩溃:方法似乎需要3个参数,但只传递了两个参数

时间:2016-11-12 17:37:16

标签: python sqlalchemy

我试图使用Unique Object' mixin'在我的SQL Alchemy项目中。但是,我显然做错了,因为我的应用程序因以下Python错误而崩溃。

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 Model定义了一个字典缓存。

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 个答案:

答案 0 :(得分:1)

您未将query传递给unique_hash。另请注意,session不属于arg,因为它是在函数def中单独指定的。因此,只有一个参数name通过kw传递给unique_hash

考虑到query功能中未使用unique_hash,您可以通过简单地删除它或使用*arg使其模糊来解决此问题:

@classmethod
def unique_hash(cls, *arg, name=None):
    return name