pymongo提供一些常用的數(shù)據(jù)類型,如:數(shù)據(jù)、字符串、日期等。如果感覺還不能滿足需求,那么還可以自定義數(shù)據(jù)類型。 首先定義一個類: class Custom(object): def __init__(self, x): self.__x = x def x(self): return self.__x 要將自定義類型的數(shù)據(jù)存入數(shù)
pymongo提供一些常用的數(shù)據(jù)類型,如:數(shù)據(jù)、字符串、日期等。如果感覺還不能滿足需求,那么還可以自定義數(shù)據(jù)類型。
首先定義一個類:
class Custom(object): def __init__(self, x): self.__x = x def x(self): return self.__x
要將自定義類型的數(shù)據(jù)存入數(shù)據(jù)庫中需要先進行編碼;將數(shù)據(jù)從數(shù)據(jù)庫讀取出來后又需要再解碼。
我們可以定義兩個方法,在插入和查詢數(shù)據(jù)時進行手動的編碼、解碼。
def encode_custom(custom): return {"_type": "custom", "x": custom.x()} def decode_custom(document): assert document["_type"] == "custom" return Custom(document["x"]) print(db.test.insert({"custom": encode_custom(Custom(5))})) print(db.test.find_one()['custom'])
手動地進行編碼雖然可行,但是還是不太方便。我們還可以使用 SONManipulator 進行自動編碼。
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 db.add_son_manipulator(Transform()) print(db.test.insert({"custom": Custom(5)})) print(db.test.find_one())
我們也可以將其編碼成二進制進行存儲。
from bson.binary import Binary def to_binary(custom): return Binary(str(custom.x()), 128) def from_binary(binary): return Custom(int(binary)) class TransformToBinary(SONManipulator): def transform_incoming(self, son, collection): for (key, value) in son.items(): if isinstance(value, Custom): son[key] = to_binary(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, Binary) and value.subtype == 128: son[key] = from_binary(value) elif isinstance(value, dict): son[key] = self.transform_outgoing(value, collection) return son db.add_son_manipulator(TransformToBinary()) print(db.test.insert({"custom": Custom(5)})) print(db.test.find_one())
原文地址:pymongo教程(3)——自定義數(shù)據(jù)類型, 感謝原作者分享。
Copyright ? 2019- 91gzw.com 版權所有 湘ICP備2023023988號-2
違法及侵權請聯(lián)系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市萬商天勤律師事務所王興未律師提供法律服務