Convert an instance of an object of a class of Python to a string monodb BSON

Does anyone know a Python library that can convert a class object to a BSON mongodb string? Currently, my only solution is to convert the class object to JSON and then JSON to BSON.

+4
source share
1 answer

This would be possible by converting an instance of the class into a dictionary (as described in the Python dictionary from the fields of the object ), and then using bson.BSON.encode in the resulting dict. Note that the __dict__ value __dict__ not contain methods, only attributes. Also note that there may be situations where this approach will not work directly.

If you have classes that you need to store in MongoDB, you might also want to consider existing ORM solutions instead of coding them. A list of them can be found at http://api.mongodb.org/python/current/tools.html

Example:

 >>> 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> >>> 
+2
source

All Articles