码迷,mamicode.com
首页 > 数据库 > 详细

python操作mongodb之六自定义类型存储

时间:2016-06-24 14:53:33      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

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

  

python操作mongodb之六自定义类型存储

标签:

原文地址:http://www.cnblogs.com/similarface/p/5614039.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!