rejson python客户端
rejson的Python项目详细描述
rejson py是一个包,它允许将对象存储、更新和查询为 在Redis数据库中使用 ReJSON module。包扩展了 redis-py与rejson的接口 api,并动态执行对象到/从的序列化/反序列化。 json。
安装
$ pip install rejson
用法示例
fromrejsonimportClient,Pathrj=Client(host='localhost',port=6379)# Set the key `obj` to some objectobj={'answer':42,'arr':[None,True,3.14],'truth':{'coord':'out there'}}rj.jsonset('obj',Path.rootPath(),obj)# Get somethingprint'Is there anybody... {}?'.format(rj.jsonget('obj',Path('.truth.coord')))# Delete something (or perhaps nothing), append something and pop itrj.jsondel('obj',Path('.arr[0]'))rj.jsonarrappend('obj',Path('.arr'),'something')print'{} popped!'.format(rj.jsonarrpop('obj',Path('.arr')))# Update something elserj.jsonset('obj',Path('.answer'),2.17)# And use just like the regular redis-py clientjp=rj.pipeline()jp.set('foo','bar')jp.jsonset('baz',Path.rootPath(),'qaz')jp.execute()
编码/解码
rejson py使用python的json。 客户端可以设置为在创建时使用自定义编码器/解码器,或者通过调用 显式地setEncoder()和 ^分别是{a12}()方法。
下面显示如何将其用于存储为 json字符串,例如:
fromjsonimportJSONEncoder,JSONDecoderfromrejsonimportClientclassCustomClass(object):"Some non-JSON-serializable"def__init__(self,s=None):ifsisnotNone:# deserialize the instance from the serializationifs.startswith('CustomClass:'):...else:raiseException('unknown format')else:# initialize the instance...def__str__(self):_str='CustomClass:'# append the instance's state to the serialization...return_str...classCustomEncoder(JSONEncoder):"A custom encoder for the custom class"defdefault(self,obj):ifisinstance(obj,CustomClass):returnstr(obj)returnjson.JSONEncoder.encode(self,obj)classTestDecoder(JSONDecoder):"A custom decoder for the custom class"defdecode(self,obj):d=json.JSONDecoder.decode(self,obj)ifisinstance(d,basestring)andd.startswith('CustomClass:'):returnCustomClass(d)returnd# Create a new instance of CustomClassobj=CustomClass()# Create a new client with the custom encoder and decoderrj=Client(encoder=CustomEncoder(),decoder=CustomDecoder())# Store the objectrj.jsonset('custom',Path.rootPath(),obj))# Retrieve itobj=rj.jsonget('custom',Path.rootPath())
API
由于rejson py公开了与redis py相同的方法,因此可以将其用作 更换。在redis的核心命令之上,客户端还添加了rejson的 词汇表和一些辅助方法。这些记录在 [api.md](api.md)文件,可通过运行生成:
$ python gendoc rejson > API.md
有关rejson命令的完整文档,请参阅ReJSON’s website。