Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธี Encode Custom Python Objects เป็น BSON ด้วย PyMongo

เพื่อ Encode Custom Python Objects เป็น BSON ด้วย PyMongo คุณต้องเขียน SONManipulator จากเอกสาร:

SONManipulator Instances อนุญาตให้ระบุ Transformations ที่จะถูก Apply อัตโนมัติโดย 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): # 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: # Recurse into sub-docs
                    son[key] = self.transform_outgoing(value, collection)
        return son

จากนั้นเพิ่มเข้า PyMongo Database Object -

db.add_son_manipulator(Transform())

โปรดทราบว่าไม่จำเป็นต้องเพิ่ม Field _type หากต้องการ Cast NumPy Array เป็น Python Array แบบเงียบๆ