Exemplo n.º 1
0
    def migrate_keys(self, host, port, keys, dest_db, timeout, *,
                     copy=False, replace=False):
        """Atomically transfer keys from one Redis instance to another one.

        Keys argument must be list/tuple of keys to migrate.
        """
        if not isinstance(host, str):
            raise TypeError("host argument must be str")
        if not isinstance(timeout, int):
            raise TypeError("timeout argument must be int")
        if not isinstance(dest_db, int):
            raise TypeError("dest_db argument must be int")
        if not isinstance(keys, (list, tuple)):
            raise TypeError("keys argument must be list or tuple")
        if not host:
            raise ValueError("Got empty host")
        if dest_db < 0:
            raise ValueError("dest_db must be greater equal 0")
        if timeout < 0:
            raise ValueError("timeout must be greater equal 0")
        if not keys:
            raise ValueError("keys must not be empty")

        flags = []
        if copy:
            flags.append(b'COPY')
        if replace:
            flags.append(b'REPLACE')
        flags.append(b'KEYS')
        flags.extend(keys)
        fut = self.execute(b'MIGRATE', host, port,
                           "", dest_db, timeout, *flags)
        return wait_ok(fut)
Exemplo n.º 2
0
 def cluster_add_slots(self, slot, *slots):
     """Assign new hash slots to receiving node."""
     slots = (slot,) + slots
     if not all(isinstance(s, int) for s in slots):
         raise TypeError("All parameters must be of type int")
     fut = self._conn.execute(b'CLUSTER', b'ADDSLOTS', *slots)
     return wait_ok(fut)
Exemplo n.º 3
0
 def cluster_del_slots(self, slot, *slots):
     """Set hash slots as unbound in receiving node."""
     slots = (slot,) + slots
     if not all(isinstance(s, int) for s in slots):
         raise TypeError("All parameters must be of type int")
     fut = self._conn.execute(b'CLUSTER', b'DELSLOTS', *slots)
     return wait_ok(fut)
Exemplo n.º 4
0
 def xgroup_create(self, stream, group_name, latest_id='$', mkstream=False):
     """Create a consumer group"""
     args = [b'CREATE', stream, group_name, latest_id]
     if mkstream:
         args.append(b'MKSTREAM')
     fut = self.execute(b'XGROUP', *args)
     return wait_ok(fut)
Exemplo n.º 5
0
    def cluster_failover(self, force=False):
        """
        Forces the slave to start a manual failover of its master instance.
        """
        command = force and b'FORCE' or b'TAKEOVER'

        fut = self.execute(b'CLUSTER', b'FAILOVER', command)
        return wait_ok(fut)
Exemplo n.º 6
0
    def psetex(self, key, milliseconds, value):
        """Set the value and expiration in milliseconds of a key.

        :raises TypeError: if milliseconds is not int
        """
        if not isinstance(milliseconds, int):
            raise TypeError("milliseconds argument must be int")
        fut = self._conn.execute(b'PSETEX', key, milliseconds, value)
        return wait_ok(fut)
Exemplo n.º 7
0
    def rename(self, key, newkey):
        """Renames key to newkey.

        :raises ValueError: if key == newkey
        """
        if key == newkey:
            raise ValueError("key and newkey are the same")
        fut = self.execute(b'RENAME', key, newkey)
        return wait_ok(fut)
Exemplo n.º 8
0
    def mset(self, key, value, *pairs):
        """Set multiple keys to multiple values.

        :raises TypeError: if len of pairs is not event number
        """
        if len(pairs) % 2 != 0:
            raise TypeError("length of pairs must be even number")
        fut = self._conn.execute(b'MSET', key, value, *pairs)
        return wait_ok(fut)
Exemplo n.º 9
0
    def flushall(self, async_op=False):
        """
        Remove all keys from all databases.

        :param async_op: lets the entire dataset to be freed asynchronously. \
        Defaults to False
        """
        if async_op:
            fut = self.execute(b'FLUSHALL', b'ASYNC')
        else:
            fut = self.execute(b'FLUSHALL')
        return wait_ok(fut)
Exemplo n.º 10
0
    def ltrim(self, key, start, stop):
        """Trim an existing list so that it will contain only the specified
        range of elements specified.

        :raises TypeError: if start or stop is not int
        """
        if not isinstance(start, int):
            raise TypeError("start argument must be int")
        if not isinstance(stop, int):
            raise TypeError("stop argument must be int")
        fut = self._conn.execute(b'LTRIM', key, start, stop)
        return wait_ok(fut)
Exemplo n.º 11
0
    def client_pause(self, timeout):
        """Stop processing commands from clients for *timeout* milliseconds.

        :raises TypeError: if timeout is not int
        :raises ValueError: if timeout is less than 0
        """
        if not isinstance(timeout, int):
            raise TypeError("timeout argument must be int")
        if timeout < 0:
            raise ValueError("timeout must be greater equal 0")
        fut = self.execute(b'CLIENT', b'PAUSE', timeout)
        return wait_ok(fut)
Exemplo n.º 12
0
    def flushdb(self, async_op=False):
        """
        Remove all keys from the current database.

        :param async_op: lets a single database to be freed asynchronously. \
        Defaults to False
        """
        if async_op:
            fut = self.execute(b'FLUSHDB', b'ASYNC')
        else:
            fut = self.execute(b'FLUSHDB')
        return wait_ok(fut)
Exemplo n.º 13
0
    def cluster_set_config_epoch(self, config_epoch):
        """Set the configuration epoch in a new node."""

        try:
            config_epoch = int(config_epoch)
        except ValueError:
            raise TypeError(
                "Expected slot to be of type int, got {}".format(
                    type(config_epoch)
                )
            )

        fut = self.execute(b'CLUSTER', b'SET-CONFIG-EPOCH', config_epoch)
        return wait_ok(fut)
Exemplo n.º 14
0
    def setex(self, key, seconds, value):
        """Set the value and expiration of a key.

        If seconds is float it will be multiplied by 1000
        coerced to int and passed to `psetex` method.

        :raises TypeError: if seconds is neither int nor float
        """
        if isinstance(seconds, float):
            return self.psetex(key, int(seconds * 1000), value)
        if not isinstance(seconds, int):
            raise TypeError("milliseconds argument must be int")
        fut = self._conn.execute(b'SETEX', key, seconds, value)
        return wait_ok(fut)
Exemplo n.º 15
0
    def mset(self, *args):
        """Set multiple keys to multiple values or unpack dict to keys & values.

        :raises TypeError: if len of args is not event number
        :raises TypeError: if len of args equals 1 and it is not a dict
        """
        data = args
        if len(args) == 1:
            if not isinstance(args[0], dict):
                raise TypeError("if one arg it should be a dict")
            data = chain.from_iterable(args[0].items())
        elif len(args) % 2 != 0:
            raise TypeError("length of pairs must be even number")
        fut = self.execute(b'MSET', *data)
        return wait_ok(fut)
Exemplo n.º 16
0
    def hmset_dict(self, key, *args, **kwargs):
        """Set multiple hash fields to multiple values.

        .. deprecated::
            HMSET is deprecated since redis 4.0.0, use HSET instead.

        dict can be passed as first positional argument:

        >>> await redis.hmset_dict(
        ...     'key', {'field1': 'value1', 'field2': 'value2'})

        or keyword arguments can be used:

        >>> await redis.hmset_dict(
        ...     'key', field1='value1', field2='value2')

        or dict argument can be mixed with kwargs:

        >>> await redis.hmset_dict(
        ...     'key', {'field1': 'value1'}, field2='value2')

        .. note:: ``dict`` and ``kwargs`` not get mixed into single dictionary,
           if both specified and both have same key(s) -- ``kwargs`` will win:

           >>> await redis.hmset_dict('key', {'foo': 'bar'}, foo='baz')
           >>> await redis.hget('key', 'foo', encoding='utf-8')
           'baz'

        """
        warnings.warn(
            "%s.hmset() is deprecated since redis 4.0.0, use %s.hset() instead"
            % (self.__class__.__name__, self.__class__.__name__),
            DeprecationWarning)

        if not args and not kwargs:
            raise TypeError("args or kwargs must be specified")
        pairs = ()
        if len(args) > 1:
            raise TypeError("single positional argument allowed")
        elif len(args) == 1:
            if not isinstance(args[0], dict):
                raise TypeError("args[0] must be dict")
            elif not args[0] and not kwargs:
                raise ValueError("args[0] is empty dict")
            pairs = chain.from_iterable(args[0].items())
        kwargs_pairs = chain.from_iterable(kwargs.items())
        return wait_ok(self.execute(b"HMSET", key, *chain(pairs,
                                                          kwargs_pairs)))
Exemplo n.º 17
0
    def hmset_dict(self, key, *args, **kwargs):
        """Set multiple hash fields to multiple values.

        dict can be passed as first positional argument:

        >>> yield from redis.hmset_dict(
        ...     'key', {'field1': 'value1', 'field2': 'value2'})

        or keyword arguments can be used:

        >>> yield from redis.hmset_dict(
        ...     'key', field1='value1', field2='value2')

        or dict argument can be mixed with kwargs:

        >>> yield from redis.hmset_dict(
        ...     'key', {'field1': 'value1'}, field2='value2')

        .. note:: ``dict`` and ``kwargs`` not get mixed into single dictionary,
           if both specified and both have same key(s) -- ``kwargs`` will win:

           >>> yield from redis.hmset_dict('key', {'foo': 'bar'}, foo='baz')
           >>> yield from redis.hget('key', 'foo', encoding='utf-8')
           'baz'

        """
        if not args and not kwargs:
            raise TypeError("args or kwargs must be specified")
        pairs = ()
        if len(args) > 1:
            raise TypeError("single positional argument allowed")
        elif len(args) == 1:
            if not isinstance(args[0], dict):
                raise TypeError("args[0] must be dict")
            elif not args[0] and not kwargs:
                raise ValueError("args[0] is empty dict")
            pairs = chain.from_iterable(args[0].items())
        kwargs_pairs = chain.from_iterable(kwargs.items())
        return wait_ok(self._conn.execute(
            b'HMSET', key, *chain(pairs, kwargs_pairs)))
Exemplo n.º 18
0
    def migrate_keys(self,
                     host,
                     port,
                     keys,
                     dest_db,
                     timeout,
                     *,
                     copy=False,
                     replace=False):
        """Atomically transfer keys from one Redis instance to another one.

        Keys argument must be list/tuple of keys to migrate.
        """
        if not isinstance(host, str):
            raise TypeError("host argument must be str")
        if not isinstance(timeout, int):
            raise TypeError("timeout argument must be int")
        if not isinstance(dest_db, int):
            raise TypeError("dest_db argument must be int")
        if not isinstance(keys, (list, tuple)):
            raise TypeError("keys argument must be list or tuple")
        if not host:
            raise ValueError("Got empty host")
        if dest_db < 0:
            raise ValueError("dest_db must be greater equal 0")
        if timeout < 0:
            raise ValueError("timeout must be greater equal 0")
        if not keys:
            raise ValueError("keys must not be empty")

        flags = []
        if copy:
            flags.append(b'COPY')
        if replace:
            flags.append(b'REPLACE')
        flags.append(b'KEYS')
        flags.extend(keys)
        fut = self.execute(b'MIGRATE', host, port, "", dest_db, timeout,
                           *flags)
        return wait_ok(fut)
Exemplo n.º 19
0
    def set(self, key, value, *, expire=0, pexpire=0, exist=None):
        """Set the string value of a key.

        :raises TypeError: if expire or pexpire is not int
        """
        if expire and not isinstance(expire, int):
            raise TypeError("expire argument must be int")
        if pexpire and not isinstance(pexpire, int):
            raise TypeError("pexpire argument must be int")

        args = []
        if expire:
            args[:] = [b"EX", expire]
        if pexpire:
            args[:] = [b"PX", pexpire]

        if exist is self.SET_IF_EXIST:
            args.append(b"XX")
        elif exist is self.SET_IF_NOT_EXIST:
            args.append(b"NX")
        fut = self.execute(b"SET", key, value, *args)
        return wait_ok(fut)
Exemplo n.º 20
0
    def set(self, key, value, *, expire=0, pexpire=0, exist=None):
        """Set the string value of a key.

        :raises TypeError: if expire or pexpire is not int
        """
        if expire and not isinstance(expire, int):
            raise TypeError("expire argument must be int")
        if pexpire and not isinstance(pexpire, int):
            raise TypeError("pexpire argument must be int")

        args = []
        if expire:
            args[:] = [b'EX', expire]
        if pexpire:
            args[:] = [b'PX', pexpire]

        if exist is self.SET_IF_EXIST:
            args.append(b'XX')
        elif exist is self.SET_IF_NOT_EXIST:
            args.append(b'NX')
        fut = self._conn.execute(b'SET', key, value, *args)
        return wait_ok(fut)
Exemplo n.º 21
0
    def migrate(self, host, port, key, dest_db, timeout, *,
                copy=False, replace=False):
        """Atomically transfer a key from a Redis instance to another one."""
        if not isinstance(host, str):
            raise TypeError("host argument must be str")
        if not isinstance(timeout, int):
            raise TypeError("timeout argument must be int")
        if not isinstance(dest_db, int):
            raise TypeError("dest_db argument must be int")
        if not host:
            raise ValueError("Got empty host")
        if dest_db < 0:
            raise ValueError("dest_db must be greater equal 0")
        if timeout < 0:
            raise ValueError("timeout must be greater equal 0")

        flags = []
        if copy:
            flags.append(b'COPY')
        if replace:
            flags.append(b'REPLACE')
        fut = self.execute(b'MIGRATE', host, port,
                           key, dest_db, timeout, *flags)
        return wait_ok(fut)
Exemplo n.º 22
0
    def migrate(self, host, port, key, dest_db, timeout, *,
                copy=False, replace=False):
        """Atomically transfer a key from a Redis instance to another one."""
        if not isinstance(host, str):
            raise TypeError("host argument must be str")
        if not isinstance(timeout, int):
            raise TypeError("timeout argument must be int")
        if not isinstance(dest_db, int):
            raise TypeError("dest_db argument must be int")
        if not host:
            raise ValueError("Got empty host")
        if dest_db < 0:
            raise ValueError("dest_db must be greater equal 0")
        if timeout < 0:
            raise ValueError("timeout must be greater equal 0")

        flags = []
        if copy:
            flags.append(b'COPY')
        if replace:
            flags.append(b'REPLACE')
        fut = self.execute(b'MIGRATE', host, port,
                           key, dest_db, timeout, *flags)
        return wait_ok(fut)
Exemplo n.º 23
0
 def cluster_reset(self, *, hard: bool = False):
     """Reset a Redis Cluster node."""
     reset = hard and b"HARD" or b"SOFT"
     fut = self.execute(b"CLUSTER", b"RESET", reset)
     return wait_ok(fut)
Exemplo n.º 24
0
 def swapdb(self, from_index, to_index):
     return wait_ok(self.execute(b'SWAPDB', from_index, to_index))
Exemplo n.º 25
0
 def cluster_reset(self, *, hard=False):
     """Reset a Redis Cluster node."""
     reset = hard and b'HARD' or b'SOFT'
     fut = self.execute(b'CLUSTER', b'RESET', reset)
     return wait_ok(fut)
Exemplo n.º 26
0
 def cluster_meet(self, ip, port):
     """Force a node cluster to handshake with another node."""
     fut = self.execute(b'CLUSTER', b'MEET', ip, port)
     return wait_ok(fut)
Exemplo n.º 27
0
 def cluster_readwrite(self):
     """
     Disables read queries for a connection to a Redis Cluster slave node.
     """
     fut = self.execute(b"READWRITE")
     return wait_ok(fut)
Exemplo n.º 28
0
 def cluster_readonly(self):
     """
     Enables read queries for a connection to a Redis Cluster slave node.
     """
     fut = self.execute(b'READONLY')
     return wait_ok(fut)
Exemplo n.º 29
0
 def script_flush(self):
     """Remove all the scripts from the script cache."""
     fut = self.execute(b"SCRIPT", b"FLUSH")
     return wait_ok(fut)
Exemplo n.º 30
0
 def script_kill(self):
     """Kill the script currently in execution."""
     fut = self.execute(b'SCRIPT', b'KILL')
     return wait_ok(fut)
Exemplo n.º 31
0
 def cluster_meet(self, ip: str, port: int):
     """Force a node cluster to handshake with another node."""
     fut = self.execute(b"CLUSTER", b"MEET", ip, port)
     return wait_ok(fut)
Exemplo n.º 32
0
 def debug_sleep(self, timeout):
     """Get debugging information about a key."""
     fut = self.execute(b'DEBUG', b'SLEEP', timeout)
     return wait_ok(fut)
Exemplo n.º 33
0
 def flushdb(self):
     """Remove all keys from the current database."""
     fut = self.execute('FLUSHDB')
     return wait_ok(fut)
Exemplo n.º 34
0
 def flushall(self):
     """Remove all keys from all databases."""
     fut = self.execute(b'FLUSHALL')
     return wait_ok(fut)
Exemplo n.º 35
0
 def xgroup_setid(self, stream, group_name, latest_id='$'):
     """Set the latest ID for a consumer group"""
     fut = self.execute(b'XGROUP', b'SETID', stream, group_name, latest_id)
     return wait_ok(fut)
Exemplo n.º 36
0
 def config_rewrite(self):
     """Rewrite the configuration file with the in memory configuration."""
     fut = self.execute(b'CONFIG', b'REWRITE')
     return wait_ok(fut)
Exemplo n.º 37
0
 def cluster_forget(self, node_id: str):
     """Remove a node from the nodes table."""
     fut = self.execute(b"CLUSTER", b"FORGET", node_id)
     return wait_ok(fut)
Exemplo n.º 38
0
 def client_setname(self, name):
     """Set the current connection name."""
     fut = self.execute(b'CLIENT', b'SETNAME', name)
     return wait_ok(fut)
Exemplo n.º 39
0
 def config_set(self, parameter, value):
     """Set a configuration parameter to the given value."""
     if not isinstance(parameter, str):
         raise TypeError("parameter must be str")
     fut = self.execute(b'CONFIG', b'SET', parameter, value)
     return wait_ok(fut)
Exemplo n.º 40
0
 def debug_sleep(self, timeout):
     """Suspend connection for timeout seconds."""
     fut = self.execute(b'DEBUG', b'SLEEP', timeout)
     return wait_ok(fut)
Exemplo n.º 41
0
 def cluster_readwrite(self):
     """
     Disables read queries for a connection to a Redis Cluster slave node.
     """
     fut = self.execute(b'READWRITE')
     return wait_ok(fut)
Exemplo n.º 42
0
 def xgroup_setid(self, stream, group_name, latest_id="$"):
     """Set the latest ID for a consumer group"""
     fut = self.execute(b"XGROUP", b"SETID", stream, group_name, latest_id)
     return wait_ok(fut)
Exemplo n.º 43
0
 def cluster_forget(self, node_id):
     """Remove a node from the nodes table."""
     fut = self.execute(b'CLUSTER', b'FORGET', node_id)
     return wait_ok(fut)
Exemplo n.º 44
0
 def cluster_readonly(self):
     """
     Enables read queries for a connection to a Redis Cluster slave node.
     """
     fut = self.execute(b"READONLY")
     return wait_ok(fut)
Exemplo n.º 45
0
 def cluster_replicate(self, node_id):
     """Reconfigure a node as a slave of the specified master node."""
     fut = self.execute(b'CLUSTER', b'REPLICATE', node_id)
     return wait_ok(fut)
Exemplo n.º 46
0
 def xgroup_create(self, stream, group_name, latest_id='$'):
     """Create a consumer group"""
     fut = self.execute(b'XGROUP', b'CREATE', stream, group_name, latest_id)
     return wait_ok(fut)
Exemplo n.º 47
0
 def cluster_save_config(self):
     """Force the node to save cluster state on disk."""
     fut = self.execute(b'CLUSTER', b'SAVECONFIG')
     return wait_ok(fut)
Exemplo n.º 48
0
 def client_setname(self, name):
     """Set the current connection name."""
     fut = self.execute(b'CLIENT', b'SETNAME', name)
     return wait_ok(fut)
Exemplo n.º 49
0
 def bgsave(self):
     """Asynchronously save the dataset to disk."""
     fut = self.execute(b'BGSAVE')
     return wait_ok(fut)
Exemplo n.º 50
0
 def cluster_replicate(self, node_id: str):
     """Reconfigure a node as a slave of the specified master node."""
     fut = self.execute(b"CLUSTER", b"REPLICATE", node_id)
     return wait_ok(fut)
Exemplo n.º 51
0
 def xgroup_destroy(self, stream, group_name):
     """Delete a consumer group"""
     fut = self.execute(b"XGROUP", b"DESTROY", stream, group_name)
     return wait_ok(fut)
Exemplo n.º 52
0
 def cluster_save_config(self):
     """Force the node to save cluster state on disk."""
     fut = self.execute(b"CLUSTER", b"SAVECONFIG")
     return wait_ok(fut)
Exemplo n.º 53
0
 def config_resetstat(self):
     """Reset the stats returned by INFO."""
     fut = self.execute(b'CONFIG', b'RESETSTAT')
     return wait_ok(fut)
Exemplo n.º 54
0
 def bgsave(self):
     """Asynchronously save the dataset to disk."""
     fut = self.execute(b'BGSAVE')
     return wait_ok(fut)
Exemplo n.º 55
0
 def bgrewriteaof(self):
     """Asynchronously rewrite the append-only file."""
     fut = self.execute(b'BGREWRITEAOF')
     return wait_ok(fut)
Exemplo n.º 56
0
 def slowlog_reset(self):
     """Resets Redis slow queries log."""
     fut = self.execute(b'SLOWLOG', b'RESET')
     return wait_ok(fut)
Exemplo n.º 57
0
 def slowlog_reset(self):
     """Resets Redis slow queries log."""
     fut = self.execute(b'SLOWLOG', b'RESET')
     return wait_ok(fut)
Exemplo n.º 58
0
 def script_kill(self):
     """Kill the script currently in execution."""
     fut = self.execute(b"SCRIPT", b"KILL")
     return wait_ok(fut)
Exemplo n.º 59
0
 def config_rewrite(self):
     """Rewrite the configuration file with the in memory configuration."""
     fut = self.execute(b'CONFIG', b'REWRITE')
     return wait_ok(fut)
Exemplo n.º 60
0
 def bgrewriteaof(self):
     """Asynchronously rewrite the append-only file."""
     fut = self.execute(b'BGREWRITEAOF')
     return wait_ok(fut)