python操作mongodb之六自定义类型存储
生活随笔
收集整理的這篇文章主要介紹了
python操作mongodb之六自定义类型存储
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
from pymongo.mongo_client import MongoClient
client=MongoClient('192.168.30.252',27017)
client=drop_database('custom_type_example')
db=client.custom_type_exampleclass Custom(object):def __init__(self,x):self.__x=xdef x(self):return self.__x###上面的類 不能自動編碼 需要手動編碼 如下
#將custom編碼成json格式
def encode_custom(custom):return {"_type": "custom", "x": custom.x()}
#將document還原成custom類
def decode_custom(document):assert document["_type"] == "custom"return Custom(document["x"])
db.test.insert({"custom": encode_custom(Custom(5))})
db.test.find_one()
decode_custom(db.test.find_one()["custom"])
decode_custom(db.test.find_one()["custom"]).x()foo=Custom(10)
foo.x()#手動顯得繁瑣,使用自動的吧
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-docsson[key] = self.transform_incoming(value, collection)return sondef 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-docsson[key] = self.transform_outgoing(value, collection)return son
#加入操縱者入數據庫
db.add_son_manipulator(Transform())
#插入對象類型
db.test.insert({"custom": Custom(5)})
db.test.find_one()
#使用對象類型
db.test.find_one()["custom"].x()
5def to_binary(custom):return Binary(str(custom.x()), 128)def from_binary(binary):return Custom(int(binary))#二進制編碼
from bson.binary import Binary
from pymongo.son_manipulator import SONManipulator
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 sondef 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())
轉載于:https://www.cnblogs.com/similarface/p/5614039.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的python操作mongodb之六自定义类型存储的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安装apache服务出错,无法启动此程序
- 下一篇: Qt之QPushButton