Ejemplo n.º 1
0
    def zadd(self, name, *args, **kwargs):
        """
        Set any number of score, element-name pairs to the key ``name``. Pairs
        can be specified in two ways:

        As *args, in the form of: score1, name1, score2, name2, ...
        or as **kwargs, in the form of: name1=score1, name2=score2, ...

        The following example would add four values to the 'my-key' key:
        redis.zadd('my-key', 1.1, 'name1', 2.2, 'name2', name3=3.3, name4=4.4)
        """
        if len(args) % 2 != 0:
            raise redis.RedisError("ZADD requires an equal number of "
                                   "values and scores")
        zset = self._db.setdefault(name, {})
        added = 0
        for score, value in zip(*[args[i::2] for i in range(2)]):
            if value not in zset:
                added += 1
            try:
                zset[value] = float(score)
            except ValueError:
                raise redis.ResponseError("value is not a valid float")
        for value, score in kwargs.items():
            if value not in zset:
                added += 1
            try:
                zset[value] = float(score)
            except ValueError:
                raise redis.ResponseError("value is not a valid float")
        return added
Ejemplo n.º 2
0
 def hincrbyfloat(self, name, key, amount=1.0):
     """Increment the value of key in hash name by floating amount"""
     try:
         amount = float(amount)
     except ValueError:
         raise redis.ResponseError("value is not a valid float")
     try:
         current = float(self._db.setdefault(name, _Hash()).get(key, '0'))
     except ValueError:
         raise redis.ResponseError("hash value is not a valid float")
     new = current + amount
     self._db[name][key] = to_bytes(new)
     return new
Ejemplo n.º 3
0
 def hincrbyfloat(self, name, key, amount=1.0):
     "Increment the value of ``key`` in hash ``name`` by floating ``amount``"
     try:
         amount = float(amount)
     except ValueError:
         raise redis.ResponseError("value is not a valid float")
     try:
         current = float(
             self._db.setdefault(name, _StrKeyDict()).get(key, '0'))
     except ValueError:
         raise redis.ResponseError("hash value is not a valid float")
     new = current + amount
     self._db[name][key] = new
     return new
Ejemplo n.º 4
0
 def get(self, name):
     value = self._db.get(name)
     if isinstance(value, _StrKeyDict):
         raise redis.ResponseError("WRONGTYPE Operation against a key "
                                   "holding the wrong kind of value")
     if value is not None:
         return to_bytes(value)
Ejemplo n.º 5
0
    def load_all_params(self, agent, key=None, errors='raise'):
        """loads agent params from the database under the given name"""
        assert errors in (
            'raise', 'warn', 'print',
            'ignore'), "errors must be 'raise','warn','print' or 'ignore'"

        if errors == 'raise':
            #Main function
            key = key or self.default_params_key
            raw = self.redis.get(key)
            if raw is None:
                raise redis.ResponseError(
                    "Params not found under key '%s' (got None)" % key)

            all_params = self.loads(raw)
            set_all_param_values(
                list(agent.agent_states) + agent.policy + agent.action_layers,
                all_params)

        else:
            #Error handling
            try:
                return self.load_all_params(agent, key=key, errors='raise')
            except:
                exc_type, exc, tb = sys.exc_info()
                if errors == 'warn':
                    warn(str(exc))
                elif errors == 'print':
                    print(str(exc))
Ejemplo n.º 6
0
 def decr(self, name, amount=1):
     try:
         self._db[name] = self._db.get(name, 0) - amount
     except TypeError:
         raise redis.ResponseError("value is not an integer or out of "
                                   "range.")
     return self._db[name]
Ejemplo n.º 7
0
 def rename(self, src, dst):
     try:
         value = self._db[src]
     except KeyError:
         raise redis.ResponseError("No such key: %s" % src)
     self._db[dst] = value
     del self._db[src]
     return True
Ejemplo n.º 8
0
def test_disabled_config_get(aggregator, redis_auth, redis_instance):
    redis_check = Redis('redisdb', {}, {})
    with mock.patch.object(redis.client.Redis, 'config_get') as get:
        get.side_effect = redis.ResponseError()
        redis_check.check(redis_instance)

    assert len(aggregator.service_checks('redis.can_connect')) == 1
    sc = aggregator.service_checks('redis.can_connect')[0]
    assert sc.tags == ['foo:bar', 'redis_host:{}'.format(HOST), 'redis_port:6379', 'redis_role:master']
Ejemplo n.º 9
0
 def mget(self, keys, *args):
     all_keys = self._list_or_args(keys, args)
     found = []
     if not all_keys:
         raise redis.ResponseError(
             "wrong number of arguments for 'mget' command")
     for key in all_keys:
         found.append(self._db.get(key))
     return found
Ejemplo n.º 10
0
 def zunionstore(self, dest, keys, aggregate=None):
     """
     Union multiple sorted sets specified by ``keys`` into
     a new sorted set, ``dest``. Scores in the destination will be
     aggregated based on the ``aggregate``, or SUM if none is provided.
     """
     if not keys:
         raise redis.ResponseError("At least one key must be specified "
                                   "for ZINTERSTORE/ZUNIONSTORE")
     self._zaggregate(dest, keys, aggregate, lambda x: True)
Ejemplo n.º 11
0
 def incr(self, name, amount=1):
     """
     Increments the value of ``key`` by ``amount``.  If no key exists,
     the value will be initialized as ``amount``
     """
     try:
         self._db[name] = self._db.get(name, 0) + amount
     except TypeError:
         raise redis.ResponseError("value is not an integer or out of "
                                   "range.")
     return self._db[name]
Ejemplo n.º 12
0
 def _get_comparator_and_val(self, value):
     try:
         if isinstance(value, string_types) and value.startswith('('):
             comparator = operator.lt
             actual_value = float(value[1:])
         else:
             comparator = operator.le
             actual_value = float(value)
     except ValueError:
         raise redis.ResponseError('min or max is not a float')
     return comparator, actual_value
Ejemplo n.º 13
0
 def _strtod_key_func(self, arg):
     # str()'ing the arg is important! Don't ever remove this.
     arg = str(arg)
     end = c_char_p()
     val = _strtod(arg, pointer(end))
     # real Redis also does an isnan check, not sure if
     # that's needed here or not.
     if end.value:
         raise redis.ResponseError(
             "One or more scores can't be converted into double")
     else:
         return val
Ejemplo n.º 14
0
 def zinterstore(self, dest, keys, aggregate=None):
     """
     Intersect multiple sorted sets specified by ``keys`` into
     a new sorted set, ``dest``. Scores in the destination will be
     aggregated based on the ``aggregate``, or SUM if none is provided.
     """
     if not keys:
         raise redis.ResponseError("At least one key must be specified "
                                   "for ZINTERSTORE/ZUNIONSTORE")
     # keys can be a list or a dict so it needs to be converted to
     # a list first.
     list_keys = list(keys)
     valid_keys = set(self._db.get(list_keys[0], {}))
     for key in list_keys[1:]:
         valid_keys.intersection_update(self._db.get(key, {}))
     return self._zaggregate(dest, keys, aggregate,
                             lambda x: x in valid_keys)
Ejemplo n.º 15
0
 def execute_command_via_connection(r, *argv, **kwargs):
     # the first time this is called, simulate an ASK exception.
     # after that behave normally.
     # capture all the requests and responses.
     if not test.execute_command_calls:
         e = redis.ResponseError("ASK 1 127.0.0.1:7003")
         test.execute_command_calls.append({'exception': e})
         raise e
     try:
         result = execute_command_via_connection_original(
             r, *argv, **kwargs)
         test.execute_command_calls.append({
             'argv': argv,
             'kwargs': kwargs,
             'result': result
         })
         return result
     except Exception as e:
         test.execute_command_calls.append({
             'argv': argv,
             'kwargs': kwargs,
             'exception': e
         })
         raise e
Ejemplo n.º 16
0
 def lset(self, name, index, value):
     try:
         self._db.get(name, [])[index] = value
     except IndexError:
         raise redis.ResponseError("index out of range")
Ejemplo n.º 17
0
 def incrbyfloat(self, name, amount=1.0):
     try:
         self._db[name] = float(self._db.get(name, '0')) + amount
     except (TypeError, ValueError):
         raise redis.ResponseError("value is not a valid float.")
     return self._db[name]