【发布时间】:2012-12-17 20:47:05
【问题描述】:
有人知道可以将类对象转换为 mongodb BSON 字符串的 Python 库吗?目前我唯一的解决方案是将类对象转换为 JSON,然后将 JSON 转换为 BSON。
【问题讨论】:
有人知道可以将类对象转换为 mongodb BSON 字符串的 Python 库吗?目前我唯一的解决方案是将类对象转换为 JSON,然后将 JSON 转换为 BSON。
【问题讨论】:
这可以通过将类实例转换为字典(如Python dictionary from an object's fields 中所述)然后在结果字典上使用bson.BSON.encode 来实现。注意__dict__ 的值不包含方法,只包含属性。另请注意,在某些情况下这种方法可能无法直接起作用。
如果您有需要存储在 MongoDB 中的类,您可能还需要考虑现有的 ORM 解决方案,而不是编写自己的代码。这些列表可以在http://api.mongodb.org/python/current/tools.html找到。
例子:
>>> import bson
>>> class Example(object):
... def __init__(self):
... self.a = 'a'
... self.b = 'b'
... def set_c(self, c):
... self.c = c
...
>>> e = Example()
>>> e
<__main__.Example object at 0x7f9448fa9150>
>>> e.__dict__
{'a': 'a', 'b': 'b'}
>>> e.set_c(123)
>>> e.__dict__
{'a': 'a', 'c': 123, 'b': 'b'}
>>> bson.BSON.encode(e.__dict__)
'\x1e\x00\x00\x00\x02a\x00\x02\x00\x00\x00a\x00\x10c\x00{\x00\x00\x00\x02b\x00\x02\x00\x00\x00b\x00\x00'
>>> bson.BSON.encode(e)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/bson/__init__.py", line 566, in encode
return cls(_dict_to_bson(document, check_keys, uuid_subtype))
TypeError: encoder expected a mapping type but got: <__main__.Example object at 0x7f9448fa9150>
>>>
【讨论】: