PyMongo使用入门(五)

2017-01-13 10:55:40来源:csdn作者:WuLex人点击

第七城市
自定义类型示例人工编码和解码:from bson import Binary
from pymongo.mongo_client import MongoClient
from pymongo.son_manipulator import SONManipulatorclient = MongoClient()
#client.drop_database("custom_type_example")
db = client.custom_type_example"""实体类"""
class Custom(object):
def __init__(self, x):
self.__x = x def x(self):
return self.__x
"""------------------------------------------------------------------"""
#人工编码和解码
def encode_custom(custom):
return {"_type": "custom", "x": custom.x()}def decode_custom(document):
assert document["_type"] == "custom"
return Custom(document["x"])db.test.insert({"custom": encode_custom(Custom(5))})
print(db.test.find_one())
print(decode_custom(db.test.find_one()["custom"]))
print(decode_custom(db.test.find_one()["custom"]).x())如图

自动编码和解码"""自动编码和解码"""
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())#这样做之后,我们可以无缝地保存和恢复Custom 实例
db.test.remove()
print(db.test.insert({"custom": Custom(5)}))
print(db.test.find_one())
print(db.test.find_one()["custom"].x())
"""------------------------------------------------------------------"""如图

二进制编码"""二进制编码"""def to_binary(custom):
return Binary(str(custom.x()).encode(), 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 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.test.remove()
db.add_son_manipulator(TransformToBinary())
db.test.insert({"custom": Custom(5)})
print(db.test.find_one())
print(db.test.find_one()["custom"].x())
""""""我们可以看到什么是真正被保存到数据库中(并验证它使用的是二进制实例)
通过清除操作者并重复查找我们的find_one():"""
db = client.custom_type_example
print(db.test.find_one())如图


第七城市

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台