将Python类对象实例转换为mongodb BSON字符串

有谁知道可以将类对象转换为
mongodb BSON字符串的
Python库?目前我唯一的解决方案是将类对象转换为JSON,然后将JSON转换为BSON. 最佳答案 这可以通过将类实例转换为字典(如
Python dictionary from an object’s fields中所述)然后在生成的dict上使用
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>
>>> 
点赞