自定义类型示例
人工编码和解码:
from bson import Binary
from pymongo.mongo_client import MongoClient
from pymongo.son_manipulator import SONManipulator
client = MongoClient()
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())
如图
![这里写图片描述](https://img-blog.csdn.net/20160906110051138)
![这里写图片描述](https://img-blog.csdn.net/20160906110155658)
自动编码和解码
"""自动编码和解码"""
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):
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:
son[key] = self.transform_outgoing(value, collection)
return son
db.add_son_manipulator(Transform())
db.test.remove()
print(db.test.insert({"custom": Custom(5)}))
print(db.test.find_one())
print(db.test.find_one()["custom"].x())
"""------------------------------------------------------------------"""
如图
![这里写图片描述](https://img-blog.csdn.net/20160906111304473)
![这里写图片描述](https://img-blog.csdn.net/20160906111323582)
二进制编码
"""二进制编码"""
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 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.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())
如图
![这里写图片描述](https://img-blog.csdn.net/20160906115626757)
![这里写图片描述](https://img-blog.csdn.net/20160906115640874)
![这里写图片描述](https://img-blog.csdn.net/20160906115712789)