예제 #1
0
    def _rc_msetnx(self, mapping):
        """
        Sets each key in the ``mapping`` dict to its corresponding value if
        none of the keys are already set
        """
        for k in iterkeys(mapping):
            if self.exists(k):
                return False

        return self._rc_mset(mapping)
예제 #2
0
    def _rc_msetnx(self, mapping):
        """
        Sets each key in the ``mapping`` dict to its corresponding value if
        none of the keys are already set
        """
        for k in iterkeys(mapping):
            if self.exists(k):
                return False

        return self._rc_mset(mapping)
예제 #3
0
파일: zset.py 프로젝트: katakumpo/niceredis
 def _zaggregate(self, command, dest, keys, aggregate=None):
     pieces = [command, dest, len(keys)]
     if isinstance(keys, dict):
         keys, weights = iterkeys(keys), itervalues(keys)
     else:
         weights = None
     pieces.extend(keys)
     if weights:
         pieces.append(Token('WEIGHTS'))
         pieces.extend(weights)
     if aggregate:
         pieces.append(Token('AGGREGATE'))
         pieces.append(aggregate)
     return self.execute_command(*pieces)
예제 #4
0
    def test_binary_lists(self, r):
        mapping = {
            b('foo bar'): [b('1'), b('2'), b('3')],
            b('foo\r\nbar\r\n'): [b('4'), b('5'), b('6')],
            b('foo\tbar\x07'): [b('7'), b('8'), b('9')],
        }
        # fill in lists
        for key, value in iteritems(mapping):
            r.rpush(key, *value)

        # check that KEYS returns all the keys as they are
        assert sorted(r.keys('*')) == sorted(list(iterkeys(mapping)))

        # check that it is possible to get list content by key name
        for key, value in iteritems(mapping):
            assert r.lrange(key, 0, -1) == value
예제 #5
0
    def test_binary_lists(self, r):
        mapping = {
            b('foo bar'): [b('1'), b('2'), b('3')],
            b('foo\r\nbar\r\n'): [b('4'), b('5'), b('6')],
            b('foo\tbar\x07'): [b('7'), b('8'), b('9')],
        }
        # fill in lists
        for key, value in iteritems(mapping):
            r.rpush(key, *value)

        # check that KEYS returns all the keys as they are
        assert sorted(r.keys('*')) == sorted(list(iterkeys(mapping)))

        # check that it is possible to get list content by key name
        for key, value in iteritems(mapping):
            assert r.lrange(key, 0, -1) == value
예제 #6
0
    def test_binary_lists(self, r):
        mapping = {
            b("foo bar"): [b("1"), b("2"), b("3")],
            b("foo\r\nbar\r\n"): [b("4"), b("5"), b("6")],
            b("foo\tbar\x07"): [b("7"), b("8"), b("9")],
        }
        # fill in lists
        for key, value in iteritems(mapping):
            r.rpush(key, *value)

        # check that KEYS returns all the keys as they are
        assert sorted(r.keys("*")) == sorted(list(iterkeys(mapping)))

        # check that it is possible to get list content by key name
        for key, value in iteritems(mapping):
            assert r.lrange(key, 0, -1) == value
예제 #7
0
 def subscribe(self, *args, **kwargs):
     """
     Subscribe to channels. Channels supplied as keyword arguments expect
     a channel name as the key and a callable as the value. A channel's
     callable will be invoked automatically when a message is received on
     that channel rather than producing a message via ``listen()`` or
     ``get_message()``.
     """
     if args:
         args = list_or_args(args[0], args[1:])
     new_channels = {}
     new_channels.update(dict.fromkeys(imap(self.encode, args)))
     for channel, handler in iteritems(kwargs):
         new_channels[self.encode(channel)] = handler
     ret_val = self.execute_command('SUBSCRIBE', *iterkeys(new_channels))
     # update the channels dict AFTER we send the command. we don't want to
     # subscribe twice to these channels, once for the command and again
     # for the reconnection.
     self.channels.update(new_channels)
     return ret_val
예제 #8
0
 def test_hkeys(self, r):
     h = {b('a1'): b('1'), b('a2'): b('2'), b('a3'): b('3')}
     r.hmset('a', h)
     local_keys = list(iterkeys(h))
     remote_keys = r.hkeys('a')
     assert (sorted(local_keys) == sorted(remote_keys))
예제 #9
0
 def test_hkeys(self, r):
     h = {b('a1'): b('1'), b('a2'): b('2'), b('a3'): b('3')}
     r.hmset('a', h)
     local_keys = list(iterkeys(h))
     remote_keys = r.hkeys('a')
     assert (sorted(local_keys) == sorted(remote_keys))
예제 #10
0
        def function(*args, **kwargs):
            if name not in StrictRedisCluster._loop_keys:
                # take care of hash tags
                tag_start = None
                key_type = hash_tag = ''
                # since we don't have "first item" in dict,
                # this list is needed in order to check hash_tag in mset({"a{a}": "a", "b":"b"})
                list_ht = []
                if isinstance(args[0], (basestring, bytes)):
                    key_type = 'string'
                    list_ht.append(args[0])
                else:
                    if isinstance(args[0], list):
                        key_type = 'list'
                        list_ht.append(args[0][0])
                    else:
                        key_type = 'dict'
                        list_ht = iterkeys(args[0])

                # check for hash tags
                for k in list_ht:
                    try:
                        tag_start = k.index('{')
                        hash_tag = k
                        break
                    except Exception as e:
                        tag_start = None

                # trigger error msg on tag keys unless we have hash tags e.g. "bar{zap}"
                if name in StrictRedisCluster._tag_keys and not tag_start:
                    try:
                        return getattr(self, '_rc_' + name)(*args, **kwargs)
                    except AttributeError:
                        raise redis.DataError("rediscluster: Command %s Not Supported (each key name has its own node)" % name)

                # get the hash key
                hkey = args[0]
                # take care of hash tags names for forcing multiple keys on the same node,
                # e.g. r.set("bar{zap}", "bar"), r.mget(["foo{foo}","bar"])
                if tag_start is not None:
                    L = list(args)
                    if key_type != 'string':
                        if key_type == 'list':
                            hkey = L[0][0][tag_start + 1:-1]
                            L[0][0] = L[0][0][0:tag_start]
                        else:
                            hkey = hash_tag[tag_start + 1:-1]
                            L[0][hash_tag[0:tag_start]] = L[0][hash_tag]
                            del L[0][hash_tag]
                    else:
                        hkey = L[0][tag_start + 1:-1]
                        L[0] = L[0][0:tag_start]

                    args = tuple(L)

                # get the node number
                node = self.getnodenamefor(hkey)
                if name in StrictRedisCluster._write_keys:
                    redisent = self.redises[node]
                elif name in StrictRedisCluster._read_keys:
                    redisent = self.redises[node + '_slave']
                else:
                    raise redis.DataError("rediscluster: Command %s Not Supported (each key name has its own node)" % name)

                # Execute the command on the server
                return getattr(redisent, name)(*args, **kwargs)

            else:

                # take care of keys that don't need to go through master and slaves redis servers
                if name not in self._loop_keys_admin:
                    try:
                        return getattr(self, '_rc_' + name)(*args, **kwargs)
                    except AttributeError:
                        raise redis.DataError("rediscluster: Command %s Not Supported (each key name has its own node)" % name)

                result = {}
                for alias, redisent in iteritems(self.redises):
                    if (name in StrictRedisCluster._write_keys and alias.find('_slave') >= 0) or (name in StrictRedisCluster._read_keys and alias.find('_slave') == -1):
                        res = None
                    else:
                        res = getattr(redisent, name)(*args, **kwargs)

                    result[alias] = res

                return result
예제 #11
0
 def test_hkeys(self, r):
     h = {b'a1': b'1', b'a2': b'2', b'a3': b'3'}
     r.hmset('a', h)
     local_keys = list(iterkeys(h))
     remote_keys = r.hkeys('a')
     assert (sorted(local_keys) == sorted(remote_keys))
예제 #12
0
 def test_hkeys(self, r):
     h = {b("a1"): b("1"), b("a2"): b("2"), b("a3"): b("3")}
     r.hmset("a", h)
     local_keys = list(iterkeys(h))
     remote_keys = r.hkeys("a")
     assert sorted(local_keys) == sorted(remote_keys)
예제 #13
0
        def function(*args, **kwargs):
            if name not in StrictRedisCluster._loop_keys:
                # take care of hash tags
                tag_start = None
                key_type = hash_tag = ''
                # since we don't have "first item" in dict,
                # this list is needed in order to check hash_tag in mset({"a{a}": "a", "b":"b"})
                list_ht = []
                if isinstance(args[0], (basestring, bytes)):
                    key_type = 'string'
                    list_ht.append(args[0])
                else:
                    if isinstance(args[0], list):
                        key_type = 'list'
                        list_ht.append(args[0][0])
                    else:
                        key_type = 'dict'
                        list_ht = iterkeys(args[0])

                # check for hash tags
                for k in list_ht:
                    try:
                        tag_start = k.index('{')
                        hash_tag = k
                        break
                    except Exception as e:
                        tag_start = None

                # trigger error msg on tag keys unless we have hash tags e.g. "bar{zap}"
                if name in StrictRedisCluster._tag_keys and not tag_start:
                    try:
                        return getattr(self, '_rc_' + name)(*args, **kwargs)
                    except AttributeError:
                        raise redis.DataError(
                            "rediscluster: Command %s Not Supported (each key name has its own node)"
                            % name)

                # get the hash key
                hkey = args[0]
                # take care of hash tags names for forcing multiple keys on the same node,
                # e.g. r.set("bar{zap}", "bar"), r.mget(["foo{foo}","bar"])
                if tag_start is not None:
                    L = list(args)
                    if key_type != 'string':
                        if key_type == 'list':
                            hkey = L[0][0][tag_start + 1:-1]
                            L[0][0] = L[0][0][0:tag_start]
                        else:
                            hkey = hash_tag[tag_start + 1:-1]
                            L[0][hash_tag[0:tag_start]] = L[0][hash_tag]
                            del L[0][hash_tag]
                    else:
                        hkey = L[0][tag_start + 1:-1]
                        L[0] = L[0][0:tag_start]

                    args = tuple(L)

                # get the node number
                node = self._getnodenamefor(hkey)
                if name in StrictRedisCluster._write_keys:
                    redisent = self.redises[node]
                elif name in StrictRedisCluster._read_keys:
                    redisent = self.redises[node + '_slave']
                else:
                    raise redis.DataError(
                        "rediscluster: Command %s Not Supported (each key name has its own node)"
                        % name)

                # Execute the command on the server
                return getattr(redisent, name)(*args, **kwargs)

            else:

                # take care of keys that don't need to go through master and slaves redis servers
                if name not in self._loop_keys_admin:
                    try:
                        return getattr(self, '_rc_' + name)(*args, **kwargs)
                    except AttributeError:
                        raise redis.DataError(
                            "rediscluster: Command %s Not Supported (each key name has its own node)"
                            % name)

                result = {}
                for alias, redisent in iteritems(self.redises):
                    if (name in StrictRedisCluster._write_keys
                            and alias.find('_slave') >= 0) or (
                                name in StrictRedisCluster._read_keys
                                and alias.find('_slave') == -1):
                        res = None
                    else:
                        res = getattr(redisent, name)(*args, **kwargs)

                    result[alias] = res

                return result