|
| 1 | +from sys import stdout |
| 2 | +import json |
| 3 | +from redis import StrictRedis, exceptions |
| 4 | +from redis._compat import (b, basestring, bytes, imap, iteritems, iterkeys, |
| 5 | + itervalues, izip, long, nativestr, unicode, |
| 6 | + safe_unicode) |
| 7 | +from .path import Path |
| 8 | + |
| 9 | +def str_path(p): |
| 10 | + "Returns the string representation of a path if it is of class Path" |
| 11 | + if isinstance(p, Path): |
| 12 | + return p.strPath |
| 13 | + else: |
| 14 | + return p |
| 15 | + |
| 16 | +def bulk_of_jsons(b): |
| 17 | + "Replace serialized JSON values with objects in a bulk array response (list)" |
| 18 | + for index, item in enumerate(b): |
| 19 | + if item is not None: |
| 20 | + b[index] = json.loads(item) |
| 21 | + return b |
| 22 | + |
| 23 | +class Client(StrictRedis): |
| 24 | + """ |
| 25 | + Implementation of ReJSON commands |
| 26 | +
|
| 27 | + This class provides an interface for ReJSON's commands and performs on-the-fly |
| 28 | + serialization/deserialization of objects to/from JSON. |
| 29 | + """ |
| 30 | + |
| 31 | + MODULE_INFO = { |
| 32 | + 'name': 'ReJSON', |
| 33 | + 'ver': 1 |
| 34 | + } |
| 35 | + |
| 36 | + MODULE_CALLBACKS = { |
| 37 | + 'JSON.DEL': lambda r: int(r), |
| 38 | + 'JSON.GET': lambda r: json.loads(r), |
| 39 | + 'JSON.MGET': bulk_of_jsons, |
| 40 | + 'JSON.SET': lambda r: r and nativestr(r) == 'OK', |
| 41 | + } |
| 42 | + |
| 43 | + def __init__(self, **kwargs): |
| 44 | + super(Client, self).__init__(**kwargs) |
| 45 | + |
| 46 | + self.__checkPrerequirements() |
| 47 | + |
| 48 | + # Inject the callbacks for the module's commands |
| 49 | + self.response_callbacks.update(self.MODULE_CALLBACKS) |
| 50 | + |
| 51 | + def __checkPrerequirements(self): |
| 52 | + "Checks that the module is ready" |
| 53 | + try: |
| 54 | + reply = self.execute_command('MODULE', 'LIST') |
| 55 | + except exceptions.ResponseError as e: |
| 56 | + if e.message.startswith('unknown command'): |
| 57 | + raise exceptions.RedisError('Modules are not supported ' |
| 58 | + 'on your Redis server - consider ' |
| 59 | + 'upgrading to a newer version.') |
| 60 | + finally: |
| 61 | + info = self.MODULE_INFO |
| 62 | + for r in reply: |
| 63 | + module = dict(zip(r[0::2], r[1::2])) |
| 64 | + if info['name'] == module['name'] and \ |
| 65 | + info['ver'] <= module['ver']: |
| 66 | + return |
| 67 | + raise exceptions.RedisError('ReJSON is not loaded - follow the ' |
| 68 | + 'instructions at http://rejson.io') |
| 69 | + |
| 70 | + def JSONDel(self, name, path=Path.rootPath()): |
| 71 | + """ |
| 72 | + Deletes the JSON value stored at key ``name`` under ``path`` |
| 73 | + """ |
| 74 | + return self.execute_command('JSON.DEL', name, str_path(path)) |
| 75 | + |
| 76 | + def JSONGet(self, name, *args): |
| 77 | + """ |
| 78 | + Get the object stored as a JSON value at key ``name`` |
| 79 | + ``args`` is zero or more paths, and defaults to root path |
| 80 | + """ |
| 81 | + pieces = [name] |
| 82 | + if len(args) == 0: |
| 83 | + pieces.append(Path.rootPath()) |
| 84 | + else: |
| 85 | + for p in args: |
| 86 | + pieces.append(str_path(p)) |
| 87 | + return self.execute_command('JSON.GET', *pieces) |
| 88 | + |
| 89 | + def JSONMGet(self, path, *args): |
| 90 | + """ |
| 91 | + Gets the objects stored as a JSON values under ``path`` from |
| 92 | + keys ``args`` |
| 93 | + """ |
| 94 | + pieces = [] |
| 95 | + pieces.extend(args) |
| 96 | + pieces.append(str_path(path)) |
| 97 | + return self.execute_command('JSON.MGET', *pieces) |
| 98 | + |
| 99 | + def JSONSet(self, name, path, obj, nx=False, xx=False): |
| 100 | + """ |
| 101 | + Set the JSON value at key ``name`` under the ``path`` to ``obj`` |
| 102 | + ``nx`` if set to True, set ``value`` only if it does not exist |
| 103 | + ``xx`` if set to True, set ``value`` only if it exists |
| 104 | + """ |
| 105 | + pieces = [name, str_path(path), json.dumps(obj)] |
| 106 | + |
| 107 | + # Handle existential modifiers |
| 108 | + if nx and xx: |
| 109 | + raise Exception('nx and xx are mutually exclusive: use one, the ' |
| 110 | + 'other or neither - but not both') |
| 111 | + elif nx: |
| 112 | + pieces.append('NX') |
| 113 | + elif xx: |
| 114 | + pieces.append('XX') |
| 115 | + |
| 116 | + return self.execute_command('JSON.SET', *pieces) |
| 117 | + |
| 118 | + def JSONType(self, name, path=Path.rootPath()): |
| 119 | + """ |
| 120 | + Gets the type of the JSON value under ``path`` from key ``name`` |
| 121 | + """ |
| 122 | + return self.execute_command('JSON.TYPE', name, str_path(path)) |
0 commit comments