Computer >> Máy Tính >  >> Lập trình >> Python

Làm cách nào để mã hóa các đối tượng python tùy chỉnh dưới dạng BSON với Pymongo?


Để mã hóa các đối tượng python tùy chỉnh dưới dạng BSON với Pymongo, bạn phải viết SONManipulator. Từ tài liệu:

Các phiên bản SONManipulator cho phép bạn chỉ định các phép biến đổi sẽ được PyMongo áp dụng tự động.

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

sau đó thêm nó vào đối tượng cơ sở dữ liệu pymongo của bạn -

db.add_son_manipulator(Transform())

Hãy lưu ý rằng bạn không cần phải thêm trường _type nếu bạn muốn truyền âm thầm một mảng numpy sang một mảng python.