跳转到主要内容

RedisJSON Python客户端

项目描述

license CircleCI pypi PyVersions GitHub issues Codecov Known Vulnerabilities

RedisJSON Python客户端

Forum Discord

弃用通知

redis-py 4.0.0开始,此库已被弃用。其功能已合并到redis-py中。请从pypy存储库中安装它。


rejson-py是一个允许将对象作为JSON文档存储、更新和查询的包,它使用Redis数据库扩展了ReJSON模块。该包通过ReJSON的API扩展了redis-py的接口,并执行对象的即时序列化和反序列化。

安装

$ pip install rejson

开发

  1. 创建一个virtualenv来管理您的Python依赖项,并确保它已激活。 virtualenv -v venv
  2. 安装pypoetry来管理您的依赖项。 pip install --user poetry
  3. 安装依赖项。 poetry install

tox默认运行所有测试。运行tox本身将运行单元测试。确保您有一个正在运行的redis,并已加载模块。

使用示例

   from rejson import Client, Path

   rj = Client(host='localhost', port=6379, decode_responses=True)

   # Set the key `obj` to some object
   obj = {
       'answer': 42,
       'arr': [None, True, 3.14],
       'truth': {
           'coord': 'out there'
       }
   }
   rj.jsonset('obj', Path.rootPath(), obj)

   # Get something
   print 'Is there anybody... {}?'.format(
       rj.jsonget('obj', Path('.truth.coord'))
   )

   # Delete something (or perhaps nothing), append something and pop it
   rj.jsondel('obj', Path('.arr[0]'))
   rj.jsonarrappend('obj', Path('.arr'), 'something')
   print '{} popped!'.format(rj.jsonarrpop('obj', Path('.arr')))

   # Update something else
   rj.jsonset('obj', Path('.answer'), 2.17)

   # And use just like the regular redis-py client
   jp = rj.pipeline()
   jp.set('foo', 'bar')
   jp.jsonset('baz', Path.rootPath(), 'qaz')
   jp.execute()

   # If you use non-ascii character in your JSON data, you can add the no_escape flag to JSON.GET command
   obj_non_ascii = {
     'non_ascii_string': 'hyvää'
   }
   rj.jsonset('non-ascii', Path.rootPath(), obj_non_ascii)
   print '{} is a non-ascii string'.format(rj.jsonget('non-ascii', Path('.non_ascii_string'), no_escape=True))

编码/解码

rejson-py 使用 Python 的 json。客户端可以在创建时设置使用自定义编码器/解码器,也可以通过分别调用 setEncoder()setDecoder() 方法来实现。

以下示例展示了如何为将自定义类存储为 JSON 字符串的情况使用它

   from json import JSONEncoder, JSONDecoder
   from rejson import Client

   class CustomClass(object):
       "Some non-JSON-serializable"
       def __init__(self, s=None):
           if s is not None:
               # deserialize the instance from the serialization
               if s.startswith('CustomClass:'):
                   ...
               else:
                   raise Exception('unknown format')
           else:
               # initialize the instance
               ...

       def __str__(self):
           _str = 'CustomClass:'
           # append the instance's state to the serialization
           ...
           return _str

       ...

   class CustomEncoder(JSONEncoder):
       "A custom encoder for the custom class"
       def default(self, obj):
           if isinstance(obj, CustomClass):
               return str(obj)
           return json.JSONEncoder.encode(self, obj)

   class TestDecoder(JSONDecoder):
       "A custom decoder for the custom class"
       def decode(self, obj):
           d = json.JSONDecoder.decode(self, obj)
           if isinstance(d, basestring) and d.startswith('CustomClass:'):
               return CustomClass(d)
           return d

   # Create a new instance of CustomClass
   obj = CustomClass()

   # Create a new client with the custom encoder and decoder
   rj = Client(encoder=CustomEncoder(), decoder=CustomDecoder())

   # Store the object
   rj.jsonset('custom', Path.rootPath(), obj))

   # Retrieve it
   obj = rj.jsonget('custom', Path.rootPath())

API

由于 rejson-py 提供与 redis-py 相同的方法,因此可以作为直接替换使用。除了 Redis 的核心命令外,客户端还添加了 ReJSON 的词汇和几个辅助方法。这些在 API.md 文件中有详细说明,该文件可以通过运行来生成。

$ python gendoc rejson > API.md

关于 ReJSON 命令的完整文档,请参阅 ReJSON 网站

许可

BSD 2-Clause

项目详情


下载文件

下载适合您平台的文件。如果您不确定要选择哪个,请了解更多关于 安装包 的信息。

源代码发行版

rejson-0.5.6.tar.gz (8.6 kB 查看哈希值)

上传时间 源代码

构建发行版

rejson-0.5.6-py3-none-any.whl (8.9 kB 查看哈希值)

上传时间 Python 3

由以下机构支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面