【问题标题】:Encoding custom python objects as BSON with pymongo使用 pymongo 将自定义 python 对象编码为 BSON
【发布时间】:2013-03-26 23:17:19
【问题描述】:

有没有办法告诉 pymongo 使用自定义编码器将 python 对象转换为 BSON?

具体来说,我需要将 numpy 数组转换为 BSON。我知道我可以手动确保每个 numpy 数组在发送到 pymongo 之前都被转换为原生 python 数组。但这是重复且容易出错的。我宁愿有一种方法来设置我的 pymongo 连接以自动执行此操作。

【问题讨论】:

    标签: python numpy pymongo bson


    【解决方案1】:

    你需要写一个SONManipulator。来自docs

    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 字段。

    【讨论】:

    • son_manipulator 目前已弃用。它们将在 v4.0 上被删除。官方的建议是在将文档传递给pymongo之前进行转换,如docs中所述
    猜你喜欢
    • 2012-08-15
    • 2015-07-31
    • 2014-11-03
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多