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

Posted similarface

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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())

  

以上是关于python操作mongodb之六自定义类型存储的主要内容,如果未能解决你的问题,请参考以下文章

王姨劝我学HarmonyOS鸿蒙2.0系列教程之六自定义View&&涂鸦项目实战!

Python每日一练——数据存储第八关:操作MongoDB数据库

python基础入门之六 —— 字典

PHP整理笔记六自定义函数

FileCoin挖矿教程之六:自定义存储布局

FileCoin挖矿教程之六:自定义存储布局