【问题标题】:Using a custom collection extending from a dict() with SqlAlchemy通过 SqlAlchemy 使用从 dict() 扩展的自定义集合
【发布时间】:2010-11-09 15:23:58
【问题描述】:

我正在尝试使用自定义集合来“连接”(或关联)两个类,但我无法做到。也许我把SqlAlchemy custom collections 的整个概念都弄错了,但让我解释一下我在做什么(看看是否有人可以给我一个提示或其他东西)

我有一个 Parent 类(你们中的一些人会从其他问题中记住它),其中包含几个连接器字段(一种列表)。其中一个连接器将存储类型为“VR”的 Child() 类的实例,另一个将存储类型为“CC”的子类。

我并不真的需要用于存储孩子的集合的持久性,但我需要它是一个特殊的类,所以它会有一些我已经实现并且需要在那里的方法。那将是“ZepConnector”类(并且,出于示例的目的,它的方法 foo() 是我需要使用的方法)。正如您在以下几行中看到的,我在 Parent 的 addChild1() 方法中随机测试了它的可用性。

--------------------- Parent.py -----

from megrok import rdb
from sqlalchemy import Column
from sqlalchemy import and_
from sqlalchemy.orm import relationship
from sqlalchemy.types import Integer
from sqlalchemy.types import String
from mylibraries.database.tests.Child import Child
from mylibraries.database.tests.Tables import testMetadata
from mylibraries.database.tests.ZepConnector import ZepConnector

class Parent(rdb.Model):
    rdb.metadata(testMetadata)
    rdb.tablename("parents_table")
    rdb.tableargs(schema='test2', useexisting=False)

    id = Column("id", Integer, primary_key=True, nullable=False, unique=True)
    _whateverField1 = Column("whatever_field1", String(16)) #Irrelevant
    _whateverField2 = Column("whatever_field2", String(16)) #Irrelevant

    child1 = relationship(
        "Child",
        uselist=True,
        primaryjoin=lambda: and_((Parent.id == Child.parent_id), (Child.type == "VR")),
        collection_class=ZepConnector("VR")
        )

    child2 = relationship(
        "Child",
        uselist=True,
        primaryjoin=lambda: and_((Parent.id == Child.parent_id), (Child.type == "CC")),
        collection_class=ZepConnector("CC")
        )

    def __init__(self):
        print "Parent __init__"
        self._whateverField1 = "Whatever1"
        self._whateverField2 = "Whatever2"
        self.child1 = ZepConnector("VR")
        self.child2 = ZepConnector("CC")

    def addChild1(self, child):
        if isinstance(child, Child):
            print("::addChild1 > Testing .foo method: " + str(self.child1.foo()))
            # The line above doesn't really makes much 
            # but testing the accessibility of the .foo() method.
            # As I'll explain later, it doesn't work
            self.child1.append(child)

    def addChild2(self, child):
        if isinstance(child, Child):
            self.child2.append(child)

请注意,我使用的是 megrok。对于那些不熟悉它的人,请允许我解释一下,它只是一个将 Python 类映射到 SqlAlchemy 映射器本身并使其在使用时更加“程序员友好”的工具Grok framework.

我猜 Parent() 类在常规 SqlAlchemy 中的映射类似于:

mapper(Parent, parents_table, properties={
    id = Column("id", Integer, primary_key=True, nullable=False, unique=True)
    _whateverField1 = Column("whatever_field1", String(16)) #Irrelevant
    _whateverField2 = Column("whatever_field2", String(16)) #Irrelevant
    child1 = relationship( # etc, etc, etc
})
#

但我 100%...呃... 90%...呃... 70% 肯定使用该工具不是让我问我要在这里问什么的原因(我的意思是:我认为不会干扰 SqlAlchemy 自定义集合的事情)

孩子是一个非常简单的类:

--------------- Child.py --------------

import random

from megrok import rdb
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy.types import Integer
from sqlalchemy.types import String
from mylibraries.database.tests.Tables import testMetadata

class Child(rdb.Model):
    rdb.metadata(testMetadata)
    rdb.tablename("children_table")
    rdb.tableargs(schema='test2', useexisting=False)

    parent_id = Column("parent_id", Integer, ForeignKey("test2.parents_table.id"), primary_key=True)
    type = Column("type", String(2), nullable=True, primary_key=True)
    hasher = Column("hasher", String(5))

    def __init__(self):
        self.type = None
        self.hasher = self.generateHasher()

    def setType(self, typeParameter):
        if typeParameter in set(["VR", "CC"]):
            self.type = typeParameter

    @staticmethod
    def generateHasher():
        retval = str()
        for i in random.sample('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 5):
            retval += i
        return retval

假设每个 Child 实例都有一个唯一的“哈希”字段,可以用作字典中的键(上面的示例与现实相去甚远,但它说明了 Child 将如何工作以及为能够创建测试)

现在是我的自定义连接器。我希望它表现为 list 或 set(更像是 set,虽然我不太介意)但它是一个类继承自dict。

-------------------- ZepConnector.py --------------------

from sqlalchemy.orm.collections import collection

class ZepConnector(dict):
    __emulates__ = list

    def __init__(self, type):
        self.type = type 
        # The 'type' will be "VR" or "CC" and it will be stamped
        # on every Child() class added through this ZepConnector

    def foo(self):
        return True

    @collection.appender
    def append(self, item):
        #Appends a child to itself
        if self.foo():
            item.setType(self.type)
            self[item.hasher] = item

    @collection.remover
    def remove(self, item):
        try:
            del self[item.hasher]
        except ValueError, e:
            print("::remove > Got exception when trying to remove entry=" + str(item.hasher) + ". The exception is: " + str(e))

    def extend(self, items):
        pass

但我不知道为什么,父类中的“ZepConnector”实例似乎不是“ZepConnector”类型,而是“InstrumentedList”:

在 Parent() 的 addChild1 方法中,我尝试测试 .foo() 方法(它应该只打印“True”)我得到这个错误:

AttributeError: 'InstrumentedList' object has no attribute 'foo'

显示整个回溯:

Traceback (most recent call last):
  File "/home/ae/mytests-cms/grokserver/eggs/zope.publisher-3.12.0-py2.4.egg/zope/publisher/publish.py", line 134, in publish
    result = publication.callObject(request, obj)
  File "/home/ae/mytests-cms/grokserver/eggs/grok-1.1rc1-py2.4.egg/grok/publication.py", line 89, in callObject
    return super(ZopePublicationSansProxy, self).callObject(request, ob)
  File "/home/ae/mytests-cms/grokserver/eggs/zope.app.publication-3.10.2-py2.4.egg/zope/app/publication/zopepublication.py", line 205, in callObject
    return mapply(ob, request.getPositionalArguments(), request)
  File "/home/ae/mytests-cms/grokserver/eggs/zope.publisher-3.12.0-py2.4.egg/zope/publisher/publish.py", line 109, in mapply
    return debug_call(obj, args)
  File "/home/ae/mytests-cms/grokserver/eggs/zope.publisher-3.12.0-py2.4.egg/zope/publisher/publish.py", line 115, in debug_call
    return obj(*args)
  File "/home/ae/mytests-cms/grokserver/eggs/grokcore.view-1.13.2-py2.4.egg/grokcore/view/components.py", line 101, in __call__
    return mapply(self.render, (), self.request)
  File "/home/ae/mytests-cms/grokserver/eggs/zope.publisher-3.12.0-py2.4.egg/zope/publisher/publish.py", line 109, in mapply
    return debug_call(obj, args)
  File "/home/ae/mytests-cms/grokserver/eggs/zope.publisher-3.12.0-py2.4.egg/zope/publisher/publish.py", line 115, in debug_call
    return obj(*args)
  File "/home/ae/mytests-cms/grokserver/src/grokserver/app.py", line 1575, in render
    mylibraries.database.tests.Test.runWholeTest()
  File "/home/ae/mytests-cms/mylibraries/database/tests/Test.py", line 54, in runWholeTest
    __test()
  File "/home/ae/mytests-cms/mylibraries/database/tests/Test.py", line 35, in __test
    parent.addChild1(child)
  File "/home/ae/mytests-cms/mylibraries/database/tests/Parent.py", line 54, in addChild1
    print("::addChild1 > Testing .foo method: " + str(self.child1.foo()))
AttributeError: 'InstrumentedList' object has no attribute 'foo'
Debug at: http://127.0.0.1:8080/_debug/view/1289342582

奇怪……ZepConnector的init方法执行正常……但是我尝试使用的时候,好像不是ZepConnector……

我又做了几个测试,但都没有成功:

在第二次尝试中,我写道:

class ZepConnector(dict):
    __emulates__ = set

但这甚至让事情变得更糟,因为我得到:

TypeError: Incompatible collection type: ZepConnector is not list-like

在第三(或第二点)尝试中,我虽然......“嗯......如果说 ZepConnector 不是列表,也许告诉 Parent() 不要在关系中使用列表可能会有所帮助...也许说明 collection_class 是 ZepConnector 使得关系中的 uselist 参数变得不必要..."

于是我写道:

child1 = relationship(
    "Child",
    uselist = False,
    primaryjoin=lambda: and_((Parent.id == Child.parent_id),(Child.type == "VR")),
    collection_class=ZepConnector("VR")
    )

但这引发了一个令人毛骨悚然的异常,谈论一个我不应该看到并且我不想看到的领域......永远...... :-D

AttributeError: 'ZepConnector' object has no attribute '_sa_instance_state'

我正在使用 Python2.4 和 SqlAlchemy 0.6.6,以防万一。

如果有人有任何想法、指导、咨询...随便...我非常感谢您与我分享...呃...我们...

提前谢谢你!

(如果您达到了这一点,那么您当然应该感谢您耐心阅读这篇巨大的帖子)

【问题讨论】:

  • 我什至还没开始理解你的代码。请把它剪下来,把你的问题分开(我敢肯定,不止一个),并对每个单独的问题做一个最小的演示。
  • @knitti > 嗯...我不认为我可以将这个问题拆分为其他问题。主要问题可以理解为:“我如何使用我的 ZepConnector 类作为 Parent() 和 Child() 类之间的 collection_class?” 感谢您阅读本文
  • 我不相信,但也没有完全放弃 :-) 能否说服您包含 AttributeError 的完整回溯?在控制流潜入sqlalchemy.util之前,我对这条线特别感兴趣
  • @knitti > 编辑我的问题:-)
  • @knitti > 天啊...这当然是一个巨大的帖子!感谢您阅读!

标签: python inheritance collections sqlalchemy


【解决方案1】:

知道了。

我也在 SqlAlchemy google 小组中问过同样的问题,我刚刚得到了答案。

http://groups.google.com/group/sqlalchemy/msg/5c8fc09a75fd4fa7

引用:

所以这是不正确的 - collection_class 接受一个类或 其他可调用作为参数 将产生一个你的实例 收藏。 ZepConnector 源 你有以下表示 ZepConnector("VR") 是 集合。你需要使用一个 拉姆达:那里。其他错误 你得到的似乎会延长 从那(这也是为什么 init 是 在 ZepConnector 上调用 - 你是 自己调用)。

感谢 Michael Bayer(以及所有试图提供帮助的人,即使阅读了如此巨大的帖子)

【讨论】:

  • 好的,那么酷。出于兴趣:你试图解决什么问题?
  • @knitti > 我无法将我自己的 ZepConnector 类用作 collection_class。我不知道是否可以使用从 dict(映射对象)扩展的类来模拟集合/列表的行为,因为在 SqlAlchemy 示例中我看到他们使用从列表扩展为列表的 collection_class 类或从 dict 扩展为 dicts 的类,但我想要从 dict 扩展的东西表现得像一个列表......我什至不知道这是否可行(我认为是但我不确定)
  • 事实证明,我唯一要做的就是在 Parent.py 中编写:collection_class=lambda:ZepConnector("VR") 而不是 collection_class= ZepConnector("VR")
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-15
  • 1970-01-01
  • 1970-01-01
  • 2016-07-08
  • 2012-03-27
  • 2013-12-31
  • 1970-01-01
相关资源
最近更新 更多