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_example

class Custom(object):
	def __init__(self,x):
		self.__x=x
	def 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-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())
#插入对象类型
db.test.insert({"custom": Custom(5)})
db.test.find_one()
#使用对象类型
db.test.find_one()["custom"].x()
5

def 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 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())

  

posted @ 2016-06-24 14:08  similarface  阅读(1714)  评论(0编辑  收藏  举报