Encoding custom python objects as BSON with pymongo

天涯浪子 提交于 2019-12-05 05:21:09

You need to write a SONManipulator. From the docs:

SONManipulator instances allow you to specify transformations to be applied automatically by 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

then add it to your pymongo database object:

db.add_son_manipulator(Transform())

Note you don't have to add the _type field if you want to silently cast a numpy array to a python array.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!