Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách encode custom Python objects thành BSON với PyMongo?

Để encode custom Python objects thành BSON với PyMongo, phải viết một SONManipulator. Theo docs:

SONManipulator instances cho phép chỉ định transform tự động áp dụng bởi 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):
                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:
                    son[key] = self.transform_outgoing(value, collection)
        return son

Thêm vào database object PyMongo:

db.add_son_manipulator(Transform())

Lưu ý: không bắt buộc thêm field _type nếu muốn cast numpy array thành Python array thầm lặng.