【发布时间】:2012-10-02 07:12:18
【问题描述】:
是否可以在 pymongo 中让collection.find() 方法返回一个从基类继承的自定义游标类,但重新定义了迭代的发生方式?
我想在迭代时从光标内的 mongo 数据实例化特定于应用程序的模型。这些文档有一个type attr,它将确定应该创建什么样的实例。我在想next 方法可以查看这些数据并决定创建和返回哪种类型。从光标继承很容易,但我不知道在哪里将它挂钩到 find() 操作?
编辑或者...
我目前正在做的是使用yield 吐出一个生成器,该生成器将在执行提取后对对象进行分类。
@classmethod
def gather(cls,place_id):
"""
Gather instances of all the shouts for one place
"""
shouts = cls.collection.find({'place_id':place_id})
for s in shouts:
yield Shout.classify(s)
@classmethod
def classify(cls,shout):
if shout.type == 1:
return Type1(dict(shout))
elif shout.type == 2:
return Type2(dict(shout))
elif shout.type == 3:
return Type3(dict(shout))
问题在于,这并没有保留封装在默认 pymongo Cursor 中的括号键访问的原始方法。
如果我要创建一个只接受一个游标实例并包装其方法的包装类,我需要重写哪些魔术方法以保留原始游标的迭代行为?我在想这样的事情:
class StuffCursor():
cursor = False
def __init__(self,cursor):
self.cursor = cursor
def __getattr__(self,attr):
#This passes off most key-based calls, like bracket-access, to the cursor
return getattr(self.cursor,attr)
这只是我能想到的,但是任何会在迭代器之上堆叠一些额外处理,然后返回修改后的迭代器的方法都可以。
【问题讨论】: