zoukankan      html  css  js  c++  java
  • 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())
    

      

  • 相关阅读:
    linux常用命令使用指南
    小赢理财招聘 测试开发、专项
    小赢理财招聘 测试开发、专项
    【模板】普通平衡树
    about乘法逆元
    luogu P2234 [HNOI2002]营业额统计
    线性筛中求莫比乌斯函数‘
    欧拉函数
    围棋
    丛林中的路
  • 原文地址:https://www.cnblogs.com/similarface/p/5614039.html
Copyright © 2011-2022 走看看