Pymongo के साथ कस्टम Python ऑब्जेक्ट्स को BSON के रूप में एन्कोड करने के लिए, आपको एक `SONManipulator` लिखना होगा। डॉक्स से:
`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): # सुनिश्चित करें कि हम सब-डॉक्स में रिकर्स करते हैं
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
इसे अपने pymongo डेटाबेस ऑब्जेक्ट में जोड़ें:
db.add_son_manipulator(Transform())
ध्यान दें कि यदि आप नम्पी ऐरे को साइलेंटली Python ऐरे में कास्ट करना चाहते हैं तो आपको `_type` फील्ड जोड़ने की आवश्यकता नहीं है।