如何使用Pymongo将自定义python对象编码为BSON?


本文向大家介绍如何使用Pymongo将自定义python对象编码为BSON?,包括了如何使用Pymongo将自定义python对象编码为BSON?的使用技巧和注意事项,需要的朋友参考一下

要将自定义python对象编码为Pymongo的BSON,必须编写SONManipulator。从文档:

SONManipulator实例允许您指定要由PyMongo自动应用的转换。

from pymongo.son_manipulator import SONManipulator
class Transform(SONManipulator):
  def transform_incoming(self, son, collection):
    for (key, value) in son.items():
      if isinstance(value, Custom):
        son[key] = encode_custom(value)
      elif isinstance(value, dict): # Make sure we recurse into sub-docs
        son[key] = self.transform_incoming(value, collection)
    return son
  def transform_outgoing(self, son, collection):
    for (key, value) in son.items():
      if isinstance(value, dict):
        if "_type" in value and value["_type"] == "custom":
          son[key] = decode_custom(value)
        else: # Again, make sure to recurse into sub-docs
          son[key] = self.transform_outgoing(value, collection)
    return son

然后将其添加到您的pymongo数据库对象-

db.add_son_manipulator(Transform())

请注意,如果要将静默的numpy数组强制转换为python数组,则不必添加_type字段。