使用pymongo将自定义python对象编码为BSON [英] Encoding custom python objects as BSON with pymongo

查看:328
本文介绍了使用pymongo将自定义python对象编码为BSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以告诉pymongo使用自定义编码器将python对象转换为BSON?

Is there a way to tell pymongo to use a custom encoder to convert python objects to BSON?

具体来说,我需要将numpy数组转换为BSON.我知道我可以手动确保将每个numpy数组转换为本地python数组,然后再将其发送到pymongo.但这是重复性的并且容易出错.我宁愿有一种方法来建立我的pymongo连接来自动执行此操作.

Specifically I need to convert numpy arrays into BSON. I know I can manually ensure every numpy array gets converted to a native python array before sending it to pymongo. But this is repetitive and error-prone. I'd much rather have a way to set up my pymongo connection to do this automatically.

推荐答案

您需要编写SONManipulator.从文档:

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

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

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

then add it to your pymongo database object:

db.add_son_manipulator(Transform())

请注意,如果您想将numpy数组静默转换为python数组,则不必添加_type字段.

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

这篇关于使用pymongo将自定义python对象编码为BSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆