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

วิธีเข้ารหัสวัตถุ python ที่กำหนดเองเป็น BSON ด้วย Pymongo


ในการเข้ารหัสอ็อบเจ็กต์ python ที่กำหนดเองเป็น BSON ด้วย Pymongo คุณต้องเขียน 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): # 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())

จดบันทึกว่าคุณไม่จำเป็นต้องเพิ่มฟิลด์ _type หากคุณต้องการส่งอาร์เรย์ numpy ไปยังอาร์เรย์ไพ ธ อนอย่างเงียบ ๆ