Welcome to redis-py’s documentation!

Indices and tables

Contents:

exception redis.AuthenticationError[source]
exception redis.AuthenticationWrongNumberOfArgsError[source]

An error to indicate that the wrong number of args were sent to the AUTH command

class redis.BlockingConnectionPool(max_connections=50, timeout=20, connection_class=<class 'redis.connection.Connection'>, queue_class=<class 'queue.LifoQueue'>, **connection_kwargs)[source]

Thread-safe blocking connection pool:

>>> from redis.client import Redis
>>> client = Redis(connection_pool=BlockingConnectionPool())

It performs the same function as the default ConnectionPool implementation, in that, it maintains a pool of reusable connections that can be shared by multiple redis clients (safely across threads if required).

The difference is that, in the event that a client tries to get a connection from the pool when all of connections are in use, rather than raising a ConnectionError (as the default ConnectionPool implementation does), it makes the client wait (“blocks”) for a specified number of seconds until a connection becomes available.

Use max_connections to increase / decrease the pool size:

>>> pool = BlockingConnectionPool(max_connections=10)

Use timeout to tell it either how many seconds to wait for a connection to become available, or to block forever:

>>> # Block forever.
>>> pool = BlockingConnectionPool(timeout=None)
>>> # Raise a ``ConnectionError`` after five seconds if a connection is
>>> # not available.
>>> pool = BlockingConnectionPool(timeout=5)
disconnect()[source]

Disconnects all connections in the pool.

get_connection(command_name, *keys, **options)[source]

Get a connection, blocking for self.timeout until a connection is available from the pool.

If the connection returned is None then creates a new connection. Because we use a last-in first-out queue, the existing connections (having been returned to the pool after the initial None values were added) will be returned before None values. This means we only create new connections when we need to, i.e.: the actual number of connections will only increase in response to demand.

make_connection()[source]

Make a fresh connection.

release(connection)[source]

Releases the connection back to the pool.

exception redis.BusyLoadingError[source]
exception redis.ChildDeadlockedError[source]

Error indicating that a child process is deadlocked after a fork()

class redis.Connection(host='localhost', port=6379, db=0, password=None, socket_timeout=None, socket_connect_timeout=None, socket_keepalive=False, socket_keepalive_options=None, socket_type=0, retry_on_timeout=False, encoding='utf-8', encoding_errors='strict', decode_responses=False, parser_class=<class 'redis.connection.PythonParser'>, socket_read_size=65536, health_check_interval=0, client_name=None, username=None, retry=None)[source]

Manages TCP communication to and from a Redis server

can_read(timeout=0)[source]

Poll the socket to see if there’s data that can be read.

check_health()[source]

Check the health of the connection with a PING/PONG

connect()[source]

Connects to the Redis server if not already connected

disconnect()[source]

Disconnects from the Redis server

on_connect()[source]

Initialize the connection, authenticate and select a database

pack_command(*args)[source]

Pack a series of arguments into the Redis protocol

pack_commands(commands)[source]

Pack multiple commands into the Redis protocol

read_response()[source]

Read the response from a previously sent command

send_command(*args, **kwargs)[source]

Pack and send a command to the Redis server

send_packed_command(command, check_health=True)[source]

Send an already packed command to the Redis server

exception redis.ConnectionError[source]
class redis.ConnectionPool(connection_class=<class 'redis.connection.Connection'>, max_connections=None, **connection_kwargs)[source]

Create a connection pool. If max_connections is set, then this object raises ConnectionError when the pool’s limit is reached.

By default, TCP connections are created unless connection_class is specified. Use UnixDomainSocketConnection for unix sockets.

Any additional keyword arguments are passed to the constructor of connection_class.

disconnect(inuse_connections=True)[source]

Disconnects connections in the pool

If inuse_connections is True, disconnect connections that are current in use, potentially by other threads. Otherwise only disconnect connections that are idle in the pool.

classmethod from_url(url, **kwargs)[source]

Return a connection pool configured from the given URL.

For example:

redis://[[username]:[password]]@localhost:6379/0
rediss://[[username]:[password]]@localhost:6379/0
unix://[[username]:[password]]@/path/to/socket.sock?db=0

Three URL schemes are supported:

The username, password, hostname, path and all querystring values are passed through urllib.parse.unquote in order to replace any percent-encoded values with their corresponding characters.

There are several ways to specify a database number. The first value found will be used:

  1. A db querystring option, e.g. redis://localhost?db=0
  2. If using the redis:// or rediss:// schemes, the path argument of the url, e.g. redis://localhost/0
  3. A db keyword argument to this function.

If none of these options are specified, the default db=0 is used.

All querystring options are cast to their appropriate Python types. Boolean arguments can be specified with string values “True”/”False” or “Yes”/”No”. Values that cannot be properly cast cause a ValueError to be raised. Once parsed, the querystring arguments and keyword arguments are passed to the ConnectionPool’s class initializer. In the case of conflicting arguments, querystring arguments always win.

get_connection(command_name, *keys, **options)[source]

Get a connection from the pool

get_encoder()[source]

Return an encoder based on encoding settings

make_connection()[source]

Create a new connection

release(connection)[source]

Releases the connection back to the pool

exception redis.DataError[source]
redis.from_url(url, **kwargs)[source]

Returns an active Redis client generated from the given database URL.

Will attempt to extract the database id from the path url fragment, if none is provided.

exception redis.InvalidResponse[source]
exception redis.PubSubError[source]
exception redis.ReadOnlyError[source]
class redis.Redis(host='localhost', port=6379, db=0, password=None, socket_timeout=None, socket_connect_timeout=None, socket_keepalive=None, socket_keepalive_options=None, connection_pool=None, unix_socket_path=None, encoding='utf-8', encoding_errors='strict', charset=None, errors=None, decode_responses=False, retry_on_timeout=False, ssl=False, ssl_keyfile=None, ssl_certfile=None, ssl_cert_reqs='required', ssl_ca_certs=None, ssl_check_hostname=False, max_connections=None, single_connection_client=False, health_check_interval=0, client_name=None, username=None, retry=None)[source]

Implementation of the Redis protocol.

This abstract class provides a Python interface to all Redis commands and an implementation of the Redis protocol.

Pipelines derive from this, implementing how the commands are sent and received to the Redis server. Based on configuration, an instance will either use a ConnectionPool, or Connection object to talk to redis.

execute_command(*args, **options)[source]

Execute a command and return a parsed response

classmethod from_url(url, **kwargs)[source]

Return a Redis client object configured from the given URL

For example:

redis://[[username]:[password]]@localhost:6379/0
rediss://[[username]:[password]]@localhost:6379/0
unix://[[username]:[password]]@/path/to/socket.sock?db=0

Three URL schemes are supported:

The username, password, hostname, path and all querystring values are passed through urllib.parse.unquote in order to replace any percent-encoded values with their corresponding characters.

There are several ways to specify a database number. The first value found will be used:

  1. A db querystring option, e.g. redis://localhost?db=0
  2. If using the redis:// or rediss:// schemes, the path argument of the url, e.g. redis://localhost/0
  3. A db keyword argument to this function.

If none of these options are specified, the default db=0 is used.

All querystring options are cast to their appropriate Python types. Boolean arguments can be specified with string values “True”/”False” or “Yes”/”No”. Values that cannot be properly cast cause a ValueError to be raised. Once parsed, the querystring arguments and keyword arguments are passed to the ConnectionPool’s class initializer. In the case of conflicting arguments, querystring arguments always win.

load_external_module(funcname, func)[source]

This function can be used to add externally defined redis modules, and their namespaces to the redis client.

funcname - A string containing the name of the function to create func - The function, being added to this class.

ex: Assume that one has a custom redis module named foomod that creates command named ‘foo.dothing’ and ‘foo.anotherthing’ in redis. To load function functions into this namespace:

from redis import Redis from foomodule import F r = Redis() r.load_external_module(“foo”, F) r.foo().dothing(‘your’, ‘arguments’)

For a concrete example see the reimport of the redisjson module in tests/test_connection.py::test_loading_external_modules

lock(name, timeout=None, sleep=0.1, blocking_timeout=None, lock_class=None, thread_local=True)[source]

Return a new Lock object using key name that mimics the behavior of threading.Lock.

If specified, timeout indicates a maximum life for the lock. By default, it will remain locked until release() is called.

sleep indicates the amount of time to sleep per loop iteration when the lock is in blocking mode and another client is currently holding the lock.

blocking_timeout indicates the maximum amount of time in seconds to spend trying to acquire the lock. A value of None indicates continue trying forever. blocking_timeout can be specified as a float or integer, both representing the number of seconds to wait.

lock_class forces the specified lock implementation.

thread_local indicates whether the lock token is placed in thread-local storage. By default, the token is placed in thread local storage so that a thread only sees its token, not a token set by another thread. Consider the following timeline:

time: 0, thread-1 acquires my-lock, with a timeout of 5 seconds.
thread-1 sets the token to “abc”
time: 1, thread-2 blocks trying to acquire my-lock using the
Lock instance.
time: 5, thread-1 has not yet completed. redis expires the lock
key.
time: 5, thread-2 acquired my-lock now that it’s available.
thread-2 sets the token to “xyz”
time: 6, thread-1 finishes its work and calls release(). if the
token is not stored in thread local storage, then thread-1 would see the token value as “xyz” and would be able to successfully release the thread-2’s lock.

In some use cases it’s necessary to disable thread local storage. For example, if you have code where one thread acquires a lock and passes that lock instance to a worker thread to release later. If thread local storage isn’t disabled in this case, the worker thread won’t see the token set by the thread that acquired the lock. Our assumption is that these cases aren’t common and as such default to using thread local storage.

parse_response(connection, command_name, **options)[source]

Parses a response from the Redis server

pipeline(transaction=True, shard_hint=None)[source]

Return a new pipeline object that can queue multiple commands for later execution. transaction indicates whether all commands should be executed atomically. Apart from making a group of operations atomic, pipelines are useful for reducing the back-and-forth overhead between the client and server.

pubsub(**kwargs)[source]

Return a Publish/Subscribe object. With this object, you can subscribe to channels and listen for messages that get published to them.

set_response_callback(command, callback)[source]

Set a custom Response Callback

transaction(func, *watches, **kwargs)[source]

Convenience method for executing the callable func as a transaction while watching all keys specified in watches. The ‘func’ callable should expect a single argument which is a Pipeline object.

exception redis.RedisError[source]
exception redis.ResponseError[source]
class redis.Sentinel(sentinels, min_other_sentinels=0, sentinel_kwargs=None, **connection_kwargs)[source]

Redis Sentinel cluster client

>>> from redis.sentinel import Sentinel
>>> sentinel = Sentinel([('localhost', 26379)], socket_timeout=0.1)
>>> master = sentinel.master_for('mymaster', socket_timeout=0.1)
>>> master.set('foo', 'bar')
>>> slave = sentinel.slave_for('mymaster', socket_timeout=0.1)
>>> slave.get('foo')
b'bar'

sentinels is a list of sentinel nodes. Each node is represented by a pair (hostname, port).

min_other_sentinels defined a minimum number of peers for a sentinel. When querying a sentinel, if it doesn’t meet this threshold, responses from that sentinel won’t be considered valid.

sentinel_kwargs is a dictionary of connection arguments used when connecting to sentinel instances. Any argument that can be passed to a normal Redis connection can be specified here. If sentinel_kwargs is not specified, any socket_timeout and socket_keepalive options specified in connection_kwargs will be used.

connection_kwargs are keyword arguments that will be used when establishing a connection to a Redis server.

discover_master(service_name)[source]

Asks sentinel servers for the Redis master’s address corresponding to the service labeled service_name.

Returns a pair (address, port) or raises MasterNotFoundError if no master is found.

discover_slaves(service_name)[source]

Returns a list of alive slaves for service service_name

execute_command(*args, **kwargs)[source]

Execute Sentinel command in sentinel nodes. once - If set to True, then execute the resulting command on a single

node at random, rather than across the entire sentinel cluster.
filter_slaves(slaves)[source]

Remove slaves that are in an ODOWN or SDOWN state

master_for(service_name, redis_class=<class 'redis.client.Redis'>, connection_pool_class=<class 'redis.sentinel.SentinelConnectionPool'>, **kwargs)[source]

Returns a redis client instance for the service_name master.

A SentinelConnectionPool class is used to retrieve the master’s address before establishing a new connection.

NOTE: If the master’s address has changed, any cached connections to the old master are closed.

By default clients will be a Redis instance. Specify a different class to the redis_class argument if you desire something different.

The connection_pool_class specifies the connection pool to use. The SentinelConnectionPool will be used by default.

All other keyword arguments are merged with any connection_kwargs passed to this class and passed to the connection pool as keyword arguments to be used to initialize Redis connections.

slave_for(service_name, redis_class=<class 'redis.client.Redis'>, connection_pool_class=<class 'redis.sentinel.SentinelConnectionPool'>, **kwargs)[source]

Returns redis client instance for the service_name slave(s).

A SentinelConnectionPool class is used to retrieve the slave’s address before establishing a new connection.

By default clients will be a Redis instance. Specify a different class to the redis_class argument if you desire something different.

The connection_pool_class specifies the connection pool to use. The SentinelConnectionPool will be used by default.

All other keyword arguments are merged with any connection_kwargs passed to this class and passed to the connection pool as keyword arguments to be used to initialize Redis connections.

class redis.SentinelConnectionPool(service_name, sentinel_manager, **kwargs)[source]

Sentinel backed connection pool.

If check_connection flag is set to True, SentinelManagedConnection sends a PING command right after establishing the connection.

rotate_slaves()[source]

Round-robin slave balancer

class redis.SentinelManagedConnection(**kwargs)[source]
connect()[source]

Connects to the Redis server if not already connected

read_response()[source]

Read the response from a previously sent command

class redis.SentinelManagedSSLConnection(**kwargs)[source]
class redis.SSLConnection(ssl_keyfile=None, ssl_certfile=None, ssl_cert_reqs='required', ssl_ca_certs=None, ssl_check_hostname=False, **kwargs)[source]
redis.StrictRedis

alias of redis.client.Redis

exception redis.TimeoutError[source]
class redis.UnixDomainSocketConnection(path='', db=0, username=None, password=None, socket_timeout=None, encoding='utf-8', encoding_errors='strict', decode_responses=False, retry_on_timeout=False, parser_class=<class 'redis.connection.PythonParser'>, socket_read_size=65536, health_check_interval=0, client_name=None, retry=None)[source]
exception redis.WatchError[source]
class redis.backoff.AbstractBackoff[source]

Backoff interface

compute(failures)[source]

Compute backoff in seconds upon failure

reset()[source]

Reset internal state before an operation. reset is called once at the beginning of every call to Retry.call_with_retry

class redis.backoff.ConstantBackoff(backoff)[source]

Constant backoff upon failure

compute(failures)[source]

Compute backoff in seconds upon failure

class redis.backoff.DecorrelatedJitterBackoff(cap, base)[source]

Decorrelated jitter backoff upon failure

compute(failures)[source]

Compute backoff in seconds upon failure

reset()[source]

Reset internal state before an operation. reset is called once at the beginning of every call to Retry.call_with_retry

class redis.backoff.EqualJitterBackoff(cap, base)[source]

Equal jitter backoff upon failure

compute(failures)[source]

Compute backoff in seconds upon failure

class redis.backoff.ExponentialBackoff(cap, base)[source]

Exponential backoff upon failure

compute(failures)[source]

Compute backoff in seconds upon failure

class redis.backoff.FullJitterBackoff(cap, base)[source]

Full jitter backoff upon failure

compute(failures)[source]

Compute backoff in seconds upon failure

class redis.backoff.NoBackoff[source]

No backoff upon failure

class redis.connection.BlockingConnectionPool(max_connections=50, timeout=20, connection_class=<class 'redis.connection.Connection'>, queue_class=<class 'queue.LifoQueue'>, **connection_kwargs)[source]

Thread-safe blocking connection pool:

>>> from redis.client import Redis
>>> client = Redis(connection_pool=BlockingConnectionPool())

It performs the same function as the default ConnectionPool implementation, in that, it maintains a pool of reusable connections that can be shared by multiple redis clients (safely across threads if required).

The difference is that, in the event that a client tries to get a connection from the pool when all of connections are in use, rather than raising a ConnectionError (as the default ConnectionPool implementation does), it makes the client wait (“blocks”) for a specified number of seconds until a connection becomes available.

Use max_connections to increase / decrease the pool size:

>>> pool = BlockingConnectionPool(max_connections=10)

Use timeout to tell it either how many seconds to wait for a connection to become available, or to block forever:

>>> # Block forever.
>>> pool = BlockingConnectionPool(timeout=None)
>>> # Raise a ``ConnectionError`` after five seconds if a connection is
>>> # not available.
>>> pool = BlockingConnectionPool(timeout=5)
disconnect()[source]

Disconnects all connections in the pool.

get_connection(command_name, *keys, **options)[source]

Get a connection, blocking for self.timeout until a connection is available from the pool.

If the connection returned is None then creates a new connection. Because we use a last-in first-out queue, the existing connections (having been returned to the pool after the initial None values were added) will be returned before None values. This means we only create new connections when we need to, i.e.: the actual number of connections will only increase in response to demand.

make_connection()[source]

Make a fresh connection.

release(connection)[source]

Releases the connection back to the pool.

class redis.connection.Connection(host='localhost', port=6379, db=0, password=None, socket_timeout=None, socket_connect_timeout=None, socket_keepalive=False, socket_keepalive_options=None, socket_type=0, retry_on_timeout=False, encoding='utf-8', encoding_errors='strict', decode_responses=False, parser_class=<class 'redis.connection.PythonParser'>, socket_read_size=65536, health_check_interval=0, client_name=None, username=None, retry=None)[source]

Manages TCP communication to and from a Redis server

can_read(timeout=0)[source]

Poll the socket to see if there’s data that can be read.

check_health()[source]

Check the health of the connection with a PING/PONG

connect()[source]

Connects to the Redis server if not already connected

disconnect()[source]

Disconnects from the Redis server

on_connect()[source]

Initialize the connection, authenticate and select a database

pack_command(*args)[source]

Pack a series of arguments into the Redis protocol

pack_commands(commands)[source]

Pack multiple commands into the Redis protocol

read_response()[source]

Read the response from a previously sent command

send_command(*args, **kwargs)[source]

Pack and send a command to the Redis server

send_packed_command(command, check_health=True)[source]

Send an already packed command to the Redis server

class redis.connection.ConnectionPool(connection_class=<class 'redis.connection.Connection'>, max_connections=None, **connection_kwargs)[source]

Create a connection pool. If max_connections is set, then this object raises ConnectionError when the pool’s limit is reached.

By default, TCP connections are created unless connection_class is specified. Use UnixDomainSocketConnection for unix sockets.

Any additional keyword arguments are passed to the constructor of connection_class.

disconnect(inuse_connections=True)[source]

Disconnects connections in the pool

If inuse_connections is True, disconnect connections that are current in use, potentially by other threads. Otherwise only disconnect connections that are idle in the pool.

classmethod from_url(url, **kwargs)[source]

Return a connection pool configured from the given URL.

For example:

redis://[[username]:[password]]@localhost:6379/0
rediss://[[username]:[password]]@localhost:6379/0
unix://[[username]:[password]]@/path/to/socket.sock?db=0

Three URL schemes are supported:

The username, password, hostname, path and all querystring values are passed through urllib.parse.unquote in order to replace any percent-encoded values with their corresponding characters.

There are several ways to specify a database number. The first value found will be used:

  1. A db querystring option, e.g. redis://localhost?db=0
  2. If using the redis:// or rediss:// schemes, the path argument of the url, e.g. redis://localhost/0
  3. A db keyword argument to this function.

If none of these options are specified, the default db=0 is used.

All querystring options are cast to their appropriate Python types. Boolean arguments can be specified with string values “True”/”False” or “Yes”/”No”. Values that cannot be properly cast cause a ValueError to be raised. Once parsed, the querystring arguments and keyword arguments are passed to the ConnectionPool’s class initializer. In the case of conflicting arguments, querystring arguments always win.

get_connection(command_name, *keys, **options)[source]

Get a connection from the pool

get_encoder()[source]

Return an encoder based on encoding settings

make_connection()[source]

Create a new connection

release(connection)[source]

Releases the connection back to the pool

redis.connection.DefaultParser

alias of redis.connection.PythonParser

class redis.connection.Encoder(encoding, encoding_errors, decode_responses)[source]

Encode strings to bytes-like and decode bytes-like to strings

decode(value, force=False)[source]

Return a unicode string from the bytes-like representation

encode(value)[source]

Return a bytestring or bytes-like representation of the value

class redis.connection.HiredisParser(socket_read_size)[source]

Parser class for connections using Hiredis

class redis.connection.PythonParser(socket_read_size)[source]

Plain Python parsing class

on_connect(connection)[source]

Called when the socket connects

on_disconnect()[source]

Called when the socket disconnects

class redis.connection.SSLConnection(ssl_keyfile=None, ssl_certfile=None, ssl_cert_reqs='required', ssl_ca_certs=None, ssl_check_hostname=False, **kwargs)[source]
class redis.connection.UnixDomainSocketConnection(path='', db=0, username=None, password=None, socket_timeout=None, encoding='utf-8', encoding_errors='strict', decode_responses=False, retry_on_timeout=False, parser_class=<class 'redis.connection.PythonParser'>, socket_read_size=65536, health_check_interval=0, client_name=None, retry=None)[source]
class redis.commands.CoreCommands[source]

A class containing all of the implemented redis commands. This class is to be used as a mixin.

acl_cat(category=None)[source]

Returns a list of categories or commands within a category.

If category is not supplied, returns a list of all categories. If category is supplied, returns a list of all commands within that category.

For more information check https://redis.io/commands/acl-cat

acl_deluser(*username)[source]

Delete the ACL for the specified ``username``s

For more information check https://redis.io/commands/acl-deluser

acl_genpass(bits=None)[source]

Generate a random password value. If bits is supplied then use this number of bits, rounded to the next multiple of 4. See: https://redis.io/commands/acl-genpass

acl_getuser(username)[source]

Get the ACL details for the specified username.

If username does not exist, return None

For more information check https://redis.io/commands/acl-getuser

acl_help()[source]

The ACL HELP command returns helpful text describing the different subcommands.

For more information check https://redis.io/commands/acl-help

acl_list()[source]

Return a list of all ACLs on the server

For more information check https://redis.io/commands/acl-list

acl_load()[source]

Load ACL rules from the configured aclfile.

Note that the server must be configured with the aclfile directive to be able to load ACL rules from an aclfile.

For more information check https://redis.io/commands/acl-load

acl_log(count=None)[source]

Get ACL logs as a list. :param int count: Get logs[0:count]. :rtype: List.

For more information check https://redis.io/commands/acl-log

acl_log_reset()[source]

Reset ACL logs. :rtype: Boolean.

For more information check https://redis.io/commands/acl-log

acl_save()[source]

Save ACL rules to the configured aclfile.

Note that the server must be configured with the aclfile directive to be able to save ACL rules to an aclfile.

For more information check https://redis.io/commands/acl-save

acl_setuser(username, enabled=False, nopass=False, passwords=None, hashed_passwords=None, categories=None, commands=None, keys=None, reset=False, reset_keys=False, reset_passwords=False)[source]

Create or update an ACL user.

Create or update the ACL for username. If the user already exists, the existing ACL is completely overwritten and replaced with the specified values.

enabled is a boolean indicating whether the user should be allowed to authenticate or not. Defaults to False.

nopass is a boolean indicating whether the can authenticate without a password. This cannot be True if passwords are also specified.

passwords if specified is a list of plain text passwords to add to or remove from the user. Each password must be prefixed with a ‘+’ to add or a ‘-’ to remove. For convenience, the value of passwords can be a simple prefixed string when adding or removing a single password.

hashed_passwords if specified is a list of SHA-256 hashed passwords to add to or remove from the user. Each hashed password must be prefixed with a ‘+’ to add or a ‘-’ to remove. For convenience, the value of hashed_passwords can be a simple prefixed string when adding or removing a single password.

categories if specified is a list of strings representing category permissions. Each string must be prefixed with either a ‘+’ to add the category permission or a ‘-’ to remove the category permission.

commands if specified is a list of strings representing command permissions. Each string must be prefixed with either a ‘+’ to add the command permission or a ‘-’ to remove the command permission.

keys if specified is a list of key patterns to grant the user access to. Keys patterns allow ‘*’ to support wildcard matching. For example, ‘*’ grants access to all keys while ‘cache:*’ grants access to all keys that are prefixed with ‘cache:’. keys should not be prefixed with a ‘~’.

reset is a boolean indicating whether the user should be fully reset prior to applying the new ACL. Setting this to True will remove all existing passwords, flags and privileges from the user and then apply the specified rules. If this is False, the user’s existing passwords, flags and privileges will be kept and any new specified rules will be applied on top.

reset_keys is a boolean indicating whether the user’s key permissions should be reset prior to applying any new key permissions specified in keys. If this is False, the user’s existing key permissions will be kept and any new specified key permissions will be applied on top.

reset_passwords is a boolean indicating whether to remove all existing passwords and the ‘nopass’ flag from the user prior to applying any new passwords specified in ‘passwords’ or ‘hashed_passwords’. If this is False, the user’s existing passwords and ‘nopass’ status will be kept and any new specified passwords or hashed_passwords will be applied on top.

For more information check https://redis.io/commands/acl-setuser

acl_users()[source]

Returns a list of all registered users on the server.

For more information check https://redis.io/commands/acl-users

acl_whoami()[source]

Get the username for the current connection

For more information check https://redis.io/commands/acl-whoami

append(key, value)[source]

Appends the string value to the value at key. If key doesn’t already exist, create it with a value of value. Returns the new length of the value at key.

For more information check https://redis.io/commands/append

bgrewriteaof()[source]

Tell the Redis server to rewrite the AOF file from data in memory.

For more information check https://redis.io/commands/bgrewriteaof

bgsave(schedule=True)[source]

Tell the Redis server to save its data to disk. Unlike save(), this method is asynchronous and returns immediately.

For more information check https://redis.io/commands/bgsave

bitcount(key, start=None, end=None)[source]

Returns the count of set bits in the value of key. Optional start and end parameters indicate which bytes to consider

For more information check https://redis.io/commands/bitcount

bitfield(key, default_overflow=None)[source]

Return a BitFieldOperation instance to conveniently construct one or more bitfield operations on key.

For more information check https://redis.io/commands/bitfield

bitop(operation, dest, *keys)[source]

Perform a bitwise operation using operation between keys and store the result in dest.

For more information check https://redis.io/commands/bitop

bitpos(key, bit, start=None, end=None)[source]

Return the position of the first bit set to 1 or 0 in a string. start and end defines search range. The range is interpreted as a range of bytes and not a range of bits, so start=0 and end=2 means to look at the first three bytes.

For more information check https://redis.io/commands/bitpos

blmove(first_list, second_list, timeout, src='LEFT', dest='RIGHT')[source]

Blocking version of lmove.

For more information check https://redis.io/commands/blmove

blpop(keys, timeout=0)[source]

LPOP a value off of the first non-empty list named in the keys list.

If none of the lists in keys has a value to LPOP, then block for timeout seconds, or until a value gets pushed on to one of the lists.

If timeout is 0, then block indefinitely.

For more information check https://redis.io/commands/blpop

brpop(keys, timeout=0)[source]

RPOP a value off of the first non-empty list named in the keys list.

If none of the lists in keys has a value to RPOP, then block for timeout seconds, or until a value gets pushed on to one of the lists.

If timeout is 0, then block indefinitely.

For more information check https://redis.io/commands/brpop

brpoplpush(src, dst, timeout=0)[source]

Pop a value off the tail of src, push it on the head of dst and then return it.

This command blocks until a value is in src or until timeout seconds elapse, whichever is first. A timeout value of 0 blocks forever.

For more information check https://redis.io/commands/brpoplpush

bzpopmax(keys, timeout=0)[source]

ZPOPMAX a value off of the first non-empty sorted set named in the keys list.

If none of the sorted sets in keys has a value to ZPOPMAX, then block for timeout seconds, or until a member gets added to one of the sorted sets.

If timeout is 0, then block indefinitely.

For more information check https://redis.io/commands/bzpopmax

bzpopmin(keys, timeout=0)[source]

ZPOPMIN a value off of the first non-empty sorted set named in the keys list.

If none of the sorted sets in keys has a value to ZPOPMIN, then block for timeout seconds, or until a member gets added to one of the sorted sets.

If timeout is 0, then block indefinitely.

For more information check https://redis.io/commands/bzpopmin

client_getname()[source]

Returns the current connection name

For more information check https://redis.io/commands/client-getname

client_getredir()[source]

Returns the ID (an integer) of the client to whom we are redirecting tracking notifications.

see: https://redis.io/commands/client-getredir

client_id()[source]

Returns the current connection id

For more information check https://redis.io/commands/client-id

client_info()[source]

Returns information and statistics about the current client connection.

For more information check https://redis.io/commands/client-info

client_kill(address)[source]

Disconnects the client at address (ip:port)

For more information check https://redis.io/commands/client-kill

client_kill_filter(_id=None, _type=None, addr=None, skipme=None, laddr=None, user=None)[source]

Disconnects client(s) using a variety of filter options :param id: Kills a client by its unique ID field :param type: Kills a client by type where type is one of ‘normal’, ‘master’, ‘slave’ or ‘pubsub’ :param addr: Kills a client by its ‘address:port’ :param skipme: If True, then the client calling the command will not get killed even if it is identified by one of the filter options. If skipme is not provided, the server defaults to skipme=True :param laddr: Kills a client by its ‘local (bind) address:port’ :param user: Kills a client for a specific user name

client_list(_type=None, client_id=[])[source]

Returns a list of currently connected clients. If type of client specified, only that type will be returned. :param _type: optional. one of the client types (normal, master,

replica, pubsub)
Parameters:client_id – optional. a list of client ids

For more information check https://redis.io/commands/client-list

client_pause(timeout)[source]

Suspend all the Redis clients for the specified amount of time :param timeout: milliseconds to pause clients

For more information check https://redis.io/commands/client-pause

client_reply(reply)[source]

Enable and disable redis server replies. reply Must be ON OFF or SKIP,

ON - The default most with server replies to commands OFF - Disable server responses to commands SKIP - Skip the response of the immediately following command.

Note: When setting OFF or SKIP replies, you will need a client object with a timeout specified in seconds, and will need to catch the TimeoutError.

The test_client_reply unit test illustrates this, and conftest.py has a client with a timeout.

See https://redis.io/commands/client-reply

client_setname(name)[source]

Sets the current connection name

For more information check https://redis.io/commands/client-setname

client_trackinginfo()[source]

Returns the information about the current client connection’s use of the server assisted client side cache.

See https://redis.io/commands/client-trackinginfo

client_unblock(client_id, error=False)[source]

Unblocks a connection by its client id. If error is True, unblocks the client with a special error message. If error is False (default), the client is unblocked using the regular timeout mechanism.

For more information check https://redis.io/commands/client-unblock

client_unpause()[source]

Unpause all redis clients

For more information check https://redis.io/commands/client-unpause

config_get(pattern='*')[source]

Return a dictionary of configuration based on the pattern

For more information check https://redis.io/commands/config-get

config_resetstat()[source]

Reset runtime statistics

For more information check https://redis.io/commands/config-resetstat

config_rewrite()[source]

Rewrite config file with the minimal change to reflect running config.

For more information check https://redis.io/commands/config-rewrite

config_set(name, value)[source]

Set config item name with value

For more information check https://redis.io/commands/config-set

copy(source, destination, destination_db=None, replace=False)[source]

Copy the value stored in the source key to the destination key.

destination_db an alternative destination database. By default, the destination key is created in the source Redis database.

replace whether the destination key should be removed before copying the value to it. By default, the value is not copied if the destination key already exists.

For more information check https://redis.io/commands/copy

dbsize()[source]

Returns the number of keys in the current database

For more information check https://redis.io/commands/dbsize

debug_object(key)[source]

Returns version specific meta information about a given key

For more information check https://redis.io/commands/debug-object

decr(name, amount=1)[source]

Decrements the value of key by amount. If no key exists, the value will be initialized as 0 - amount

For more information check https://redis.io/commands/decr

decrby(name, amount=1)[source]

Decrements the value of key by amount. If no key exists, the value will be initialized as 0 - amount

For more information check https://redis.io/commands/decrby

delete(*names)[source]

Delete one or more keys specified by names

dump(name)[source]

Return a serialized version of the value stored at the specified key. If key does not exist a nil bulk reply is returned.

For more information check https://redis.io/commands/dump

echo(value)[source]

Echo the string back from the server

For more information check https://redis.io/commands/echo

eval(script, numkeys, *keys_and_args)[source]

Execute the Lua script, specifying the numkeys the script will touch and the key names and argument values in keys_and_args. Returns the result of the script.

In practice, use the object returned by register_script. This function exists purely for Redis API completion.

For more information check https://redis.io/commands/eval

evalsha(sha, numkeys, *keys_and_args)[source]

Use the sha to execute a Lua script already registered via EVAL or SCRIPT LOAD. Specify the numkeys the script will touch and the key names and argument values in keys_and_args. Returns the result of the script.

In practice, use the object returned by register_script. This function exists purely for Redis API completion.

For more information check https://redis.io/commands/evalsha

exists(*names)[source]

Returns the number of names that exist

For more information check https://redis.io/commands/exists

expire(name, time)[source]

Set an expire flag on key name for time seconds. time can be represented by an integer or a Python timedelta object.

For more information check https://redis.io/commands/expire

expireat(name, when)[source]

Set an expire flag on key name. when can be represented as an integer indicating unix time or a Python datetime object.

For more information check https://redis.io/commands/expireat

flushall(asynchronous=False)[source]

Delete all keys in all databases on the current host.

asynchronous indicates whether the operation is executed asynchronously by the server.

For more information check https://redis.io/commands/flushall

flushdb(asynchronous=False)[source]

Delete all keys in the current database.

asynchronous indicates whether the operation is executed asynchronously by the server.

For more information check https://redis.io/commands/flushdb

geoadd(name, values, nx=False, xx=False, ch=False)[source]

Add the specified geospatial items to the specified key identified by the name argument. The Geospatial items are given as ordered members of the values argument, each item or place is formed by the triad longitude, latitude and name.

Note: You can use ZREM to remove elements.

nx forces ZADD to only create new elements and not to update scores for elements that already exist.

xx forces ZADD to only update scores of elements that already exist. New elements will not be added.

ch modifies the return value to be the numbers of elements changed. Changed elements include new elements that were added and elements whose scores changed.

For more information check https://redis.io/commands/geoadd

geodist(name, place1, place2, unit=None)[source]

Return the distance between place1 and place2 members of the name key. The units must be one of the following : m, km mi, ft. By default meters are used.

For more information check https://redis.io/commands/geodist

geohash(name, *values)[source]

Return the geo hash string for each item of values members of the specified key identified by the name argument.

For more information check https://redis.io/commands/geohash

geopos(name, *values)[source]

Return the positions of each item of values as members of the specified key identified by the name argument. Each position is represented by the pairs lon and lat.

For more information check https://redis.io/commands/geopos

georadius(name, longitude, latitude, radius, unit=None, withdist=False, withcoord=False, withhash=False, count=None, sort=None, store=None, store_dist=None, any=False)[source]

Return the members of the specified key identified by the name argument which are within the borders of the area specified with the latitude and longitude location and the maximum distance from the center specified by the radius value.

The units must be one of the following : m, km mi, ft. By default

withdist indicates to return the distances of each place.

withcoord indicates to return the latitude and longitude of each place.

withhash indicates to return the geohash string of each place.

count indicates to return the number of elements up to N.

sort indicates to return the places in a sorted way, ASC for nearest to fairest and DESC for fairest to nearest.

store indicates to save the places names in a sorted set named with a specific key, each element of the destination sorted set is populated with the score got from the original geo sorted set.

store_dist indicates to save the places names in a sorted set named with a specific key, instead of store the sorted set destination score is set with the distance.

For more information check https://redis.io/commands/georadius

georadiusbymember(name, member, radius, unit=None, withdist=False, withcoord=False, withhash=False, count=None, sort=None, store=None, store_dist=None, any=False)[source]

This command is exactly like georadius with the sole difference that instead of taking, as the center of the area to query, a longitude and latitude value, it takes the name of a member already existing inside the geospatial index represented by the sorted set.

For more information check https://redis.io/commands/georadiusbymember

geosearch(name, member=None, longitude=None, latitude=None, unit='m', radius=None, width=None, height=None, sort=None, count=None, any=False, withcoord=False, withdist=False, withhash=False)[source]

Return the members of specified key identified by the name argument, which are within the borders of the area specified by a given shape. This command extends the GEORADIUS command, so in addition to searching within circular areas, it supports searching within rectangular areas. This command should be used in place of the deprecated GEORADIUS and GEORADIUSBYMEMBER commands. member Use the position of the given existing

member in the sorted set. Can’t be given with longitude and latitude.

longitude and latitude Use the position given by this coordinates. Can’t be given with member radius Similar to GEORADIUS, search inside circular area according the given radius. Can’t be given with height and width. height and width Search inside an axis-aligned rectangle, determined by the given height and width. Can’t be given with radius unit must be one of the following : m, km, mi, ft. m for meters (the default value), km for kilometers, mi for miles and ft for feet. sort indicates to return the places in a sorted way, ASC for nearest to farest and DESC for farest to nearest. count limit the results to the first count matching items. any is set to True, the command will return as soon as enough matches are found. Can’t be provided without count withdist indicates to return the distances of each place. withcoord indicates to return the latitude and longitude of each place. withhash indicates to return the geohash string of each place.

For more information check https://redis.io/commands/geosearch

geosearchstore(dest, name, member=None, longitude=None, latitude=None, unit='m', radius=None, width=None, height=None, sort=None, count=None, any=False, storedist=False)[source]

This command is like GEOSEARCH, but stores the result in dest. By default, it stores the results in the destination sorted set with their geospatial information. if store_dist set to True, the command will stores the items in a sorted set populated with their distance from the center of the circle or box, as a floating-point number.

For more information check https://redis.io/commands/geosearchstore

get(name)[source]

Return the value at key name, or None if the key doesn’t exist

For more information check https://redis.io/commands/get

getbit(name, offset)[source]

Returns a boolean indicating the value of offset in name

For more information check https://redis.io/commands/getbit

getdel(name)[source]

Get the value at key name and delete the key. This command is similar to GET, except for the fact that it also deletes the key on success (if and only if the key’s value type is a string).

For more information check https://redis.io/commands/getdel

getex(name, ex=None, px=None, exat=None, pxat=None, persist=False)[source]

Get the value of key and optionally set its expiration. GETEX is similar to GET, but is a write command with additional options. All time parameters can be given as datetime.timedelta or integers.

ex sets an expire flag on key name for ex seconds.

px sets an expire flag on key name for px milliseconds.

exat sets an expire flag on key name for ex seconds, specified in unix time.

pxat sets an expire flag on key name for ex milliseconds, specified in unix time.

persist remove the time to live associated with name.

For more information check https://redis.io/commands/getex

getrange(key, start, end)[source]

Returns the substring of the string value stored at key, determined by the offsets start and end (both are inclusive)

For more information check https://redis.io/commands/getrange

getset(name, value)[source]

Sets the value at key name to value and returns the old value at key name atomically.

As per Redis 6.2, GETSET is considered deprecated. Please use SET with GET parameter in new code.

For more information check https://redis.io/commands/getset

hdel(name, *keys)[source]

Delete keys from hash name

For more information check https://redis.io/commands/hdel

hexists(name, key)[source]

Returns a boolean indicating if key exists within hash name

For more information check https://redis.io/commands/hexists

hget(name, key)[source]

Return the value of key within the hash name

For more information check https://redis.io/commands/hget

hgetall(name)[source]

Return a Python dict of the hash’s name/value pairs

For more information check https://redis.io/commands/hgetall

hincrby(name, key, amount=1)[source]

Increment the value of key in hash name by amount

For more information check https://redis.io/commands/hincrby

hincrbyfloat(name, key, amount=1.0)[source]

Increment the value of key in hash name by floating amount

For more information check https://redis.io/commands/hincrbyfloat

hkeys(name)[source]

Return the list of keys within hash name

For more information check https://redis.io/commands/hkeys

hlen(name)[source]

Return the number of elements in hash name

For more information check https://redis.io/commands/hlen

hmget(name, keys, *args)[source]

Returns a list of values ordered identically to keys

For more information check https://redis.io/commands/hmget

hmset(name, mapping)[source]

Set key to value within hash name for each corresponding key and value from the mapping dict.

For more information check https://redis.io/commands/hmset

hrandfield(key, count=None, withvalues=False)[source]

Return a random field from the hash value stored at key.

count: if the argument is positive, return an array of distinct fields. If called with a negative count, the behavior changes and the command is allowed to return the same field multiple times. In this case, the number of returned fields is the absolute value of the specified count. withvalues: The optional WITHVALUES modifier changes the reply so it includes the respective values of the randomly selected hash fields.

For more information check https://redis.io/commands/hrandfield

hscan(name, cursor=0, match=None, count=None)[source]

Incrementally return key/value slices in a hash. Also return a cursor indicating the scan position.

match allows for filtering the keys by pattern

count allows for hint the minimum number of returns

For more information check https://redis.io/commands/hscan

hscan_iter(name, match=None, count=None)[source]

Make an iterator using the HSCAN command so that the client doesn’t need to remember the cursor position.

match allows for filtering the keys by pattern

count allows for hint the minimum number of returns

hset(name, key=None, value=None, mapping=None)[source]

Set key to value within hash name, mapping accepts a dict of key/value pairs that will be added to hash name. Returns the number of fields that were added.

For more information check https://redis.io/commands/hset

hsetnx(name, key, value)[source]

Set key to value within hash name if key does not exist. Returns 1 if HSETNX created a field, otherwise 0.

For more information check https://redis.io/commands/hsetnx

hstrlen(name, key)[source]

Return the number of bytes stored in the value of key within hash name

For more information check https://redis.io/commands/hstrlen

hvals(name)[source]

Return the list of values within hash name

For more information check https://redis.io/commands/hvals

incr(name, amount=1)[source]

Increments the value of key by amount. If no key exists, the value will be initialized as amount

For more information check https://redis.io/commands/incr

incrby(name, amount=1)[source]

Increments the value of key by amount. If no key exists, the value will be initialized as amount

For more information check https://redis.io/commands/incrby

incrbyfloat(name, amount=1.0)[source]

Increments the value at key name by floating amount. If no key exists, the value will be initialized as amount

For more information check https://redis.io/commands/incrbyfloat

info(section=None)[source]

Returns a dictionary containing information about the Redis server

The section option can be used to select a specific section of information

The section option is not supported by older versions of Redis Server, and will generate ResponseError

For more information check https://redis.io/commands/info

keys(pattern='*')[source]

Returns a list of keys matching pattern

For more information check https://redis.io/commands/keys

lastsave()[source]

Return a Python datetime object representing the last time the Redis database was saved to disk

For more information check https://redis.io/commands/lastsave

lindex(name, index)[source]

Return the item from list name at position index

Negative indexes are supported and will return an item at the end of the list

For more information check https://redis.io/commands/lindex

linsert(name, where, refvalue, value)[source]

Insert value in list name either immediately before or after [where] refvalue

Returns the new length of the list on success or -1 if refvalue is not in the list.

For more information check https://redis.io/commands/linsert

llen(name)[source]

Return the length of the list name

For more information check https://redis.io/commands/llen

lmove(first_list, second_list, src='LEFT', dest='RIGHT')[source]

Atomically returns and removes the first/last element of a list, pushing it as the first/last element on the destination list. Returns the element being popped and pushed.

For more information check https://redis.io/commands/lmov

lolwut(*version_numbers)[source]

Get the Redis version and a piece of generative computer art

See: https://redis.io/commands/lolwut

lpop(name, count=None)[source]

Removes and returns the first elements of the list name.

By default, the command pops a single element from the beginning of the list. When provided with the optional count argument, the reply will consist of up to count elements, depending on the list’s length.

For more information check https://redis.io/commands/lpop

lpos(name, value, rank=None, count=None, maxlen=None)[source]

Get position of value within the list name

If specified, rank indicates the “rank” of the first element to return in case there are multiple copies of value in the list. By default, LPOS returns the position of the first occurrence of value in the list. When rank 2, LPOS returns the position of the second value in the list. If rank is negative, LPOS searches the list in reverse. For example, -1 would return the position of the last occurrence of value and -2 would return the position of the next to last occurrence of value.

If specified, count indicates that LPOS should return a list of up to count positions. A count of 2 would return a list of up to 2 positions. A count of 0 returns a list of all positions matching value. When count is specified and but value does not exist in the list, an empty list is returned.

If specified, maxlen indicates the maximum number of list elements to scan. A maxlen of 1000 will only return the position(s) of items within the first 1000 entries in the list. A maxlen of 0 (the default) will scan the entire list.

For more information check https://redis.io/commands/lpos

lpush(name, *values)[source]

Push values onto the head of the list name

For more information check https://redis.io/commands/lpush

lpushx(name, *values)[source]

Push value onto the head of the list name if name exists

For more information check https://redis.io/commands/lpushx

lrange(name, start, end)[source]

Return a slice of the list name between position start and end

start and end can be negative numbers just like Python slicing notation

For more information check https://redis.io/commands/lrange

lrem(name, count, value)[source]

Remove the first count occurrences of elements equal to value from the list stored at name.

The count argument influences the operation in the following ways:

count > 0: Remove elements equal to value moving from head to tail. count < 0: Remove elements equal to value moving from tail to head. count = 0: Remove all elements equal to value.

For more information check https://redis.io/commands/lrem

lset(name, index, value)[source]

Set position of list name to value

For more information check https://redis.io/commands/lset

ltrim(name, start, end)[source]

Trim the list name, removing all values not within the slice between start and end

start and end can be negative numbers just like Python slicing notation

For more information check https://redis.io/commands/ltrim

memory_malloc_stats()[source]

Return an internal statistics report from the memory allocator.

See: https://redis.io/commands/memory-malloc-stats

memory_purge()[source]

Attempts to purge dirty pages for reclamation by allocator

For more information check https://redis.io/commands/memory-purge

memory_stats()[source]

Return a dictionary of memory stats

For more information check https://redis.io/commands/memory-stats

memory_usage(key, samples=None)[source]

Return the total memory usage for key, its value and associated administrative overheads.

For nested data structures, samples is the number of elements to sample. If left unspecified, the server’s default is 5. Use 0 to sample all elements.

For more information check https://redis.io/commands/memory-usage

mget(keys, *args)[source]

Returns a list of values ordered identically to keys

For more information check https://redis.io/commands/mget

migrate(host, port, keys, destination_db, timeout, copy=False, replace=False, auth=None)[source]

Migrate 1 or more keys from the current Redis server to a different server specified by the host, port and destination_db.

The timeout, specified in milliseconds, indicates the maximum time the connection between the two servers can be idle before the command is interrupted.

If copy is True, the specified keys are NOT deleted from the source server.

If replace is True, this operation will overwrite the keys on the destination server if they exist.

If auth is specified, authenticate to the destination server with the password provided.

For more information check https://redis.io/commands/migrate

module_list()[source]

Returns a list of dictionaries containing the name and version of all loaded modules.

For more information check https://redis.io/commands/module-list

module_load(path, *args)[source]

Loads the module from path. Passes all *args to the module, during loading. Raises ModuleError if a module is not found at path.

For more information check https://redis.io/commands/module-load

module_unload(name)[source]

Unloads the module name. Raises ModuleError if name is not in loaded modules.

For more information check https://redis.io/commands/module-unload

move(name, db)[source]

Moves the key name to a different Redis database db

For more information check https://redis.io/commands/move

mset(mapping)[source]

Sets key/values based on a mapping. Mapping is a dictionary of key/value pairs. Both keys and values should be strings or types that can be cast to a string via str().

For more information check https://redis.io/commands/mset

msetnx(mapping)[source]

Sets key/values based on a mapping if none of the keys are already set. Mapping is a dictionary of key/value pairs. Both keys and values should be strings or types that can be cast to a string via str(). Returns a boolean indicating if the operation was successful.

For more information check https://redis.io/commands/msetnx

object(infotype, key)[source]

Return the encoding, idletime, or refcount about the key

persist(name)[source]

Removes an expiration on name

For more information check https://redis.io/commands/persist

pexpire(name, time)[source]

Set an expire flag on key name for time milliseconds. time can be represented by an integer or a Python timedelta object.

For more information check https://redis.io/commands/pexpire

pexpireat(name, when)[source]

Set an expire flag on key name. when can be represented as an integer representing unix time in milliseconds (unix time * 1000) or a Python datetime object.

For more information check https://redis.io/commands/pexpireat

pfadd(name, *values)[source]

Adds the specified elements to the specified HyperLogLog.

For more information check https://redis.io/commands/pfadd

pfcount(*sources)[source]

Return the approximated cardinality of the set observed by the HyperLogLog at key(s).

For more information check https://redis.io/commands/pfcount

pfmerge(dest, *sources)[source]

Merge N different HyperLogLogs into a single one.

For more information check https://redis.io/commands/pfmerge

ping()[source]

Ping the Redis server

For more information check https://redis.io/commands/ping

psetex(name, time_ms, value)[source]

Set the value of key name to value that expires in time_ms milliseconds. time_ms can be represented by an integer or a Python timedelta object

For more information check https://redis.io/commands/psetex

pttl(name)[source]

Returns the number of milliseconds until the key name will expire

For more information check https://redis.io/commands/pttl

publish(channel, message)[source]

Publish message on channel. Returns the number of subscribers the message was delivered to.

For more information check https://redis.io/commands/publish

pubsub_channels(pattern='*')[source]

Return a list of channels that have at least one subscriber

For more information check https://redis.io/commands/pubsub-channels

pubsub_numpat()[source]

Returns the number of subscriptions to patterns

For more information check https://redis.io/commands/pubsub-numpat

pubsub_numsub(*args)[source]

Return a list of (channel, number of subscribers) tuples for each channel given in *args

For more information check https://redis.io/commands/pubsub-numsub

quit()[source]

Ask the server to close the connection.

For more information check https://redis.io/commands/quit

randomkey()[source]

Returns the name of a random key

For more information check https://redis.io/commands/randomkey

readonly()[source]

Enables read queries for a connection to a Redis Cluster replica node.

For more information check https://redis.io/commands/readonly

readwrite()[source]

Disables read queries for a connection to a Redis Cluster slave node.

For more information check https://redis.io/commands/readwrite

register_script(script)[source]

Register a Lua script specifying the keys it will touch. Returns a Script object that is callable and hides the complexity of deal with scripts, keys, and shas. This is the preferred way to work with Lua scripts.

rename(src, dst)[source]

Rename key src to dst

For more information check https://redis.io/commands/rename

renamenx(src, dst)[source]

Rename key src to dst if dst doesn’t already exist

For more information check https://redis.io/commands/renamenx

replicaof(*args)[source]

Update the replication settings of a redis replica, on the fly. Examples of valid arguments include:

NO ONE (set no replication) host port (set to the host and port of a redis server)

For more information check https://redis.io/commands/replicaof

restore(name, ttl, value, replace=False, absttl=False, idletime=None, frequency=None)[source]

Create a key using the provided serialized value, previously obtained using DUMP.

replace allows an existing key on name to be overridden. If it’s not specified an error is raised on collision.

absttl if True, specified ttl should represent an absolute Unix timestamp in milliseconds in which the key will expire. (Redis 5.0 or greater).

idletime Used for eviction, this is the number of seconds the key must be idle, prior to execution.

frequency Used for eviction, this is the frequency counter of the object stored at the key, prior to execution.

For more information check https://redis.io/commands/restore

rpop(name, count=None)[source]

Removes and returns the last elements of the list name.

By default, the command pops a single element from the end of the list. When provided with the optional count argument, the reply will consist of up to count elements, depending on the list’s length.

For more information check https://redis.io/commands/rpop

rpoplpush(src, dst)[source]

RPOP a value off of the src list and atomically LPUSH it on to the dst list. Returns the value.

For more information check https://redis.io/commands/rpoplpush

rpush(name, *values)[source]

Push values onto the tail of the list name

For more information check https://redis.io/commands/rpush

rpushx(name, value)[source]

Push value onto the tail of the list name if name exists

For more information check https://redis.io/commands/rpushx

sadd(name, *values)[source]

Add value(s) to set name

For more information check https://redis.io/commands/sadd

save()[source]

Tell the Redis server to save its data to disk, blocking until the save is complete

For more information check https://redis.io/commands/save

scan(cursor=0, match=None, count=None, _type=None)[source]

Incrementally return lists of key names. Also return a cursor indicating the scan position.

match allows for filtering the keys by pattern

count provides a hint to Redis about the number of keys to
return per batch.
_type filters the returned values by a particular Redis type.
Stock Redis instances allow for the following types: HASH, LIST, SET, STREAM, STRING, ZSET Additionally, Redis modules can expose other types as well.

For more information check https://redis.io/commands/scan

scan_iter(match=None, count=None, _type=None)[source]

Make an iterator using the SCAN command so that the client doesn’t need to remember the cursor position.

match allows for filtering the keys by pattern

count provides a hint to Redis about the number of keys to
return per batch.
_type filters the returned values by a particular Redis type.
Stock Redis instances allow for the following types: HASH, LIST, SET, STREAM, STRING, ZSET Additionally, Redis modules can expose other types as well.
scard(name)[source]

Return the number of elements in set name

For more information check https://redis.io/commands/scard

script_exists(*args)[source]

Check if a script exists in the script cache by specifying the SHAs of each script as args. Returns a list of boolean values indicating if if each already script exists in the cache.

For more information check https://redis.io/commands/script-exists

script_flush(sync_type=None)[source]

Flush all scripts from the script cache. sync_type is by default SYNC (synchronous) but it can also be

ASYNC.

For more information check https://redis.io/commands/script-flush

script_kill()[source]

Kill the currently executing Lua script

For more information check https://redis.io/commands/script-kill

script_load(script)[source]

Load a Lua script into the script cache. Returns the SHA.

For more information check https://redis.io/commands/script-load

sdiff(keys, *args)[source]

Return the difference of sets specified by keys

For more information check https://redis.io/commands/sdiff

sdiffstore(dest, keys, *args)[source]

Store the difference of sets specified by keys into a new set named dest. Returns the number of keys in the new set.

For more information check https://redis.io/commands/sdiffstore

set(name, value, ex=None, px=None, nx=False, xx=False, keepttl=False, get=False, exat=None, pxat=None)[source]

Set the value at key name to value

ex sets an expire flag on key name for ex seconds.

px sets an expire flag on key name for px milliseconds.

nx if set to True, set the value at key name to value only
if it does not exist.
xx if set to True, set the value at key name to value only
if it already exists.
keepttl if True, retain the time to live associated with the key.
(Available since Redis 6.0)
get if True, set the value at key name to value and return
the old value stored at key, or None if the key did not exist. (Available since Redis 6.2)
exat sets an expire flag on key name for ex seconds,
specified in unix time.
pxat sets an expire flag on key name for ex milliseconds,
specified in unix time.

For more information check https://redis.io/commands/set

setbit(name, offset, value)[source]

Flag the offset in name as value. Returns a boolean indicating the previous value of offset.

For more information check https://redis.io/commands/setbit

setex(name, time, value)[source]

Set the value of key name to value that expires in time seconds. time can be represented by an integer or a Python timedelta object.

For more information check https://redis.io/commands/setex

setnx(name, value)[source]

Set the value of key name to value if key doesn’t exist

For more information check https://redis.io/commands/setnx

setrange(name, offset, value)[source]

Overwrite bytes in the value of name starting at offset with value. If offset plus the length of value exceeds the length of the original value, the new value will be larger than before. If offset exceeds the length of the original value, null bytes will be used to pad between the end of the previous value and the start of what’s being injected.

Returns the length of the new string.

For more information check https://redis.io/commands/setrange

shutdown(save=False, nosave=False)[source]

Shutdown the Redis server. If Redis has persistence configured, data will be flushed before shutdown. If the “save” option is set, a data flush will be attempted even if there is no persistence configured. If the “nosave” option is set, no data flush will be attempted. The “save” and “nosave” options cannot both be set.

For more information check https://redis.io/commands/shutdown

sinter(keys, *args)[source]

Return the intersection of sets specified by keys

For more information check https://redis.io/commands/sinter

sinterstore(dest, keys, *args)[source]

Store the intersection of sets specified by keys into a new set named dest. Returns the number of keys in the new set.

For more information check https://redis.io/commands/sinterstore

sismember(name, value)[source]

Return a boolean indicating if value is a member of set name

For more information check https://redis.io/commands/sismember

slaveof(host=None, port=None)[source]

Set the server to be a replicated slave of the instance identified by the host and port. If called without arguments, the instance is promoted to a master instead.

For more information check https://redis.io/commands/slaveof

slowlog_get(num=None)[source]

Get the entries from the slowlog. If num is specified, get the most recent num items.

For more information check https://redis.io/commands/slowlog-get

slowlog_len()[source]

Get the number of items in the slowlog

For more information check https://redis.io/commands/slowlog-len

slowlog_reset()[source]

Remove all items in the slowlog

For more information check https://redis.io/commands/slowlog-reset

smembers(name)[source]

Return all members of the set name

For more information check https://redis.io/commands/smembers

smismember(name, values, *args)[source]

Return whether each value in values is a member of the set name as a list of bool in the order of values

For more information check https://redis.io/commands/smismember

smove(src, dst, value)[source]

Move value from set src to set dst atomically

For more information check https://redis.io/commands/smove

sort(name, start=None, num=None, by=None, get=None, desc=False, alpha=False, store=None, groups=False)[source]

Sort and return the list, set or sorted set at name.

start and num allow for paging through the sorted data

by allows using an external key to weight and sort the items.
Use an “*” to indicate where in the key the item value is located
get allows for returning items from external keys rather than the
sorted data itself. Use an “*” to indicate where in the key the item value is located

desc allows for reversing the sort

alpha allows for sorting lexicographically rather than numerically

store allows for storing the result of the sort into
the key store
groups if set to True and if get contains at least two
elements, sort will return a list of tuples, each containing the values fetched from the arguments to get.

For more information check https://redis.io/commands/sort

spop(name, count=None)[source]

Remove and return a random member of set name

For more information check https://redis.io/commands/spop

srandmember(name, number=None)[source]

If number is None, returns a random member of set name.

If number is supplied, returns a list of number random members of set name. Note this is only available when running Redis 2.6+.

For more information check https://redis.io/commands/srandmember

srem(name, *values)[source]

Remove values from set name

For more information check https://redis.io/commands/srem

sscan(name, cursor=0, match=None, count=None)[source]

Incrementally return lists of elements in a set. Also return a cursor indicating the scan position.

match allows for filtering the keys by pattern

count allows for hint the minimum number of returns

For more information check https://redis.io/commands/sscan

sscan_iter(name, match=None, count=None)[source]

Make an iterator using the SSCAN command so that the client doesn’t need to remember the cursor position.

match allows for filtering the keys by pattern

count allows for hint the minimum number of returns

stralgo(algo, value1, value2, specific_argument='strings', len=False, idx=False, minmatchlen=None, withmatchlen=False)[source]

Implements complex algorithms that operate on strings. Right now the only algorithm implemented is the LCS algorithm (longest common substring). However new algorithms could be implemented in the future.

algo Right now must be LCS value1 and value2 Can be two strings or two keys specific_argument Specifying if the arguments to the algorithm will be keys or strings. strings is the default. len Returns just the len of the match. idx Returns the match positions in each string. minmatchlen Restrict the list of matches to the ones of a given minimal length. Can be provided only when idx set to True. withmatchlen Returns the matches with the len of the match. Can be provided only when idx set to True.

For more information check https://redis.io/commands/stralgo

strlen(name)[source]

Return the number of bytes stored in the value of name

For more information check https://redis.io/commands/strlen

substr(name, start, end=-1)[source]

Return a substring of the string at key name. start and end are 0-based integers specifying the portion of the string to return.

sunion(keys, *args)[source]

Return the union of sets specified by keys

For more information check https://redis.io/commands/sunion

sunionstore(dest, keys, *args)[source]

Store the union of sets specified by keys into a new set named dest. Returns the number of keys in the new set.

For more information check https://redis.io/commands/sunionstore

swapdb(first, second)[source]

Swap two databases

For more information check https://redis.io/commands/swapdb

time()[source]

Returns the server time as a 2-item tuple of ints: (seconds since epoch, microseconds into this second).

For more information check https://redis.io/commands/time

touch(*args)[source]

Alters the last access time of a key(s) *args. A key is ignored if it does not exist.

For more information check https://redis.io/commands/touch

ttl(name)[source]

Returns the number of seconds until the key name will expire

For more information check https://redis.io/commands/ttl

type(name)[source]

Returns the type of key name

For more information check https://redis.io/commands/type

Unlink one or more keys specified by names

For more information check https://redis.io/commands/unlink

unwatch()[source]

Unwatches the value at key name, or None of the key doesn’t exist

For more information check https://redis.io/commands/unwatch

wait(num_replicas, timeout)[source]

Redis synchronous replication That returns the number of replicas that processed the query when we finally have at least num_replicas, or when the timeout was reached.

For more information check https://redis.io/commands/wait

watch(*names)[source]

Watches the values at keys names, or None if the key doesn’t exist

For more information check https://redis.io/commands/type

xack(name, groupname, *ids)[source]

Acknowledges the successful processing of one or more messages. name: name of the stream. groupname: name of the consumer group. *ids: message ids to acknowledge.

For more information check https://redis.io/commands/xack

xadd(name, fields, id='*', maxlen=None, approximate=True, nomkstream=False, minid=None, limit=None)[source]

Add to a stream. name: name of the stream fields: dict of field/value pairs to insert into the stream id: Location to insert this record. By default it is appended. maxlen: truncate old stream members beyond this size. Can’t be specified with minid. approximate: actual stream length may be slightly more than maxlen nomkstream: When set to true, do not make a stream minid: the minimum id in the stream to query. Can’t be specified with maxlen. limit: specifies the maximum number of entries to retrieve

For more information check https://redis.io/commands/xadd

xautoclaim(name, groupname, consumername, min_idle_time, start_id=0, count=None, justid=False)[source]

Transfers ownership of pending stream entries that match the specified criteria. Conceptually, equivalent to calling XPENDING and then XCLAIM, but provides a more straightforward way to deal with message delivery failures via SCAN-like semantics. name: name of the stream. groupname: name of the consumer group. consumername: name of a consumer that claims the message. min_idle_time: filter messages that were idle less than this amount of milliseconds. start_id: filter messages with equal or greater ID. count: optional integer, upper limit of the number of entries that the command attempts to claim. Set to 100 by default. justid: optional boolean, false by default. Return just an array of IDs of messages successfully claimed, without returning the actual message

For more information check https://redis.io/commands/xautoclaim

xclaim(name, groupname, consumername, min_idle_time, message_ids, idle=None, time=None, retrycount=None, force=False, justid=False)[source]

Changes the ownership of a pending message. name: name of the stream. groupname: name of the consumer group. consumername: name of a consumer that claims the message. min_idle_time: filter messages that were idle less than this amount of milliseconds message_ids: non-empty list or tuple of message IDs to claim idle: optional. Set the idle time (last time it was delivered) of the

message in ms
time: optional integer. This is the same as idle but instead of a
relative amount of milliseconds, it sets the idle time to a specific Unix time (in milliseconds).
retrycount: optional integer. set the retry counter to the specified
value. This counter is incremented every time a message is delivered again.
force: optional boolean, false by default. Creates the pending message
entry in the PEL even if certain specified IDs are not already in the PEL assigned to a different client.
justid: optional boolean, false by default. Return just an array of IDs

of messages successfully claimed, without returning the actual message

For more information check https://redis.io/commands/xclaim

xdel(name, *ids)[source]

Deletes one or more messages from a stream. name: name of the stream. *ids: message ids to delete.

For more information check https://redis.io/commands/xdel

xgroup_create(name, groupname, id='$', mkstream=False)[source]

Create a new consumer group associated with a stream. name: name of the stream. groupname: name of the consumer group. id: ID of the last item in the stream to consider already delivered.

For more information check https://redis.io/commands/xgroup-create

xgroup_createconsumer(name, groupname, consumername)[source]

Consumers in a consumer group are auto-created every time a new consumer name is mentioned by some command. They can be explicitly created by using this command. name: name of the stream. groupname: name of the consumer group. consumername: name of consumer to create.

See: https://redis.io/commands/xgroup-createconsumer

xgroup_delconsumer(name, groupname, consumername)[source]

Remove a specific consumer from a consumer group. Returns the number of pending messages that the consumer had before it was deleted. name: name of the stream. groupname: name of the consumer group. consumername: name of consumer to delete

For more information check https://redis.io/commands/xgroup-delconsumer

xgroup_destroy(name, groupname)[source]

Destroy a consumer group. name: name of the stream. groupname: name of the consumer group.

For more information check https://redis.io/commands/xgroup-destroy

xgroup_setid(name, groupname, id)[source]

Set the consumer group last delivered ID to something else. name: name of the stream. groupname: name of the consumer group. id: ID of the last item in the stream to consider already delivered.

For more information check https://redis.io/commands/xgroup-setid

xinfo_consumers(name, groupname)[source]

Returns general information about the consumers in the group. name: name of the stream. groupname: name of the consumer group.

For more information check https://redis.io/commands/xinfo-consumers

xinfo_groups(name)[source]

Returns general information about the consumer groups of the stream. name: name of the stream.

For more information check https://redis.io/commands/xinfo-groups

xinfo_stream(name, full=False)[source]

Returns general information about the stream. name: name of the stream. full: optional boolean, false by default. Return full summary

For more information check https://redis.io/commands/xinfo-stream

xlen(name)[source]

Returns the number of elements in a given stream.

For more information check https://redis.io/commands/xlen

xpending(name, groupname)[source]

Returns information about pending messages of a group. name: name of the stream. groupname: name of the consumer group.

For more information check https://redis.io/commands/xpending

xpending_range(name, groupname, idle=None, min=None, max=None, count=None, consumername=None)[source]

Returns information about pending messages, in a range.

name: name of the stream. groupname: name of the consumer group. idle: available from version 6.2. filter entries by their idle-time, given in milliseconds (optional). min: minimum stream ID. max: maximum stream ID. count: number of messages to return consumername: name of a consumer to filter by (optional).

xrange(name, min='-', max='+', count=None)[source]

Read stream values within an interval. name: name of the stream. start: first stream ID. defaults to ‘-‘,

meaning the earliest available.
finish: last stream ID. defaults to ‘+’,
meaning the latest available.
count: if set, only return this many items, beginning with the
earliest available.

For more information check https://redis.io/commands/xrange

xread(streams, count=None, block=None)[source]

Block and monitor multiple streams for new data. streams: a dict of stream names to stream IDs, where

IDs indicate the last ID already seen.
count: if set, only return this many items, beginning with the
earliest available.

block: number of milliseconds to wait, if nothing already present.

For more information check https://redis.io/commands/xread

xreadgroup(groupname, consumername, streams, count=None, block=None, noack=False)[source]

Read from a stream via a consumer group. groupname: name of the consumer group. consumername: name of the requesting consumer. streams: a dict of stream names to stream IDs, where

IDs indicate the last ID already seen.
count: if set, only return this many items, beginning with the
earliest available.

block: number of milliseconds to wait, if nothing already present. noack: do not add messages to the PEL

For more information check https://redis.io/commands/xreadgroup

xrevrange(name, max='+', min='-', count=None)[source]

Read stream values within an interval, in reverse order. name: name of the stream start: first stream ID. defaults to ‘+’,

meaning the latest available.
finish: last stream ID. defaults to ‘-‘,
meaning the earliest available.
count: if set, only return this many items, beginning with the
latest available.

For more information check https://redis.io/commands/xrevrange

xtrim(name, maxlen=None, approximate=True, minid=None, limit=None)[source]

Trims old messages from a stream. name: name of the stream. maxlen: truncate old stream messages beyond this size Can’t be specified with minid. approximate: actual stream length may be slightly more than maxlen minid: the minimum id in the stream to query Can’t be specified with maxlen. limit: specifies the maximum number of entries to retrieve

For more information check https://redis.io/commands/xtrim

zadd(name, mapping, nx=False, xx=False, ch=False, incr=False, gt=None, lt=None)[source]

Set any number of element-name, score pairs to the key name. Pairs are specified as a dict of element-names keys to score values.

nx forces ZADD to only create new elements and not to update scores for elements that already exist.

xx forces ZADD to only update scores of elements that already exist. New elements will not be added.

ch modifies the return value to be the numbers of elements changed. Changed elements include new elements that were added and elements whose scores changed.

incr modifies ZADD to behave like ZINCRBY. In this mode only a single element/score pair can be specified and the score is the amount the existing score will be incremented by. When using this mode the return value of ZADD will be the new score of the element.

LT Only update existing elements if the new score is less than the current score. This flag doesn’t prevent adding new elements.

GT Only update existing elements if the new score is greater than the current score. This flag doesn’t prevent adding new elements.

The return value of ZADD varies based on the mode specified. With no options, ZADD returns the number of new elements added to the sorted set.

NX, LT, and GT are mutually exclusive options.

See: https://redis.io/commands/ZADD

zcard(name)[source]

Return the number of elements in the sorted set name

For more information check https://redis.io/commands/zcard

zcount(name, min, max)[source]

Returns the number of elements in the sorted set at key name with a score between min and max.

For more information check https://redis.io/commands/zcount

zdiff(keys, withscores=False)[source]

Returns the difference between the first and all successive input sorted sets provided in keys.

For more information check https://redis.io/commands/zdiff

zdiffstore(dest, keys)[source]

Computes the difference between the first and all successive input sorted sets provided in keys and stores the result in dest.

For more information check https://redis.io/commands/zdiffstore

zincrby(name, amount, value)[source]

Increment the score of value in sorted set name by amount

For more information check https://redis.io/commands/zincrby

zinter(keys, aggregate=None, withscores=False)[source]

Return the intersect of multiple sorted sets specified by keys. With the aggregate option, it is possible to specify how the results of the union are aggregated. This option defaults to SUM, where the score of an element is summed across the inputs where it exists. When this option is set to either MIN or MAX, the resulting set will contain the minimum or maximum score of an element across the inputs where it exists.

For more information check https://redis.io/commands/zinter

zinterstore(dest, keys, aggregate=None)[source]

Intersect multiple sorted sets specified by keys into a new sorted set, dest. Scores in the destination will be aggregated based on the aggregate. This option defaults to SUM, where the score of an element is summed across the inputs where it exists. When this option is set to either MIN or MAX, the resulting set will contain the minimum or maximum score of an element across the inputs where it exists.

For more information check https://redis.io/commands/zinterstore

zlexcount(name, min, max)[source]

Return the number of items in the sorted set name between the lexicographical range min and max.

For more information check https://redis.io/commands/zlexcount

zmscore(key, members)[source]

Returns the scores associated with the specified members in the sorted set stored at key. members should be a list of the member name. Return type is a list of score. If the member does not exist, a None will be returned in corresponding position.

For more information check https://redis.io/commands/zmscore

zpopmax(name, count=None)[source]

Remove and return up to count members with the highest scores from the sorted set name.

For more information check https://redis.io/commands/zpopmax

zpopmin(name, count=None)[source]

Remove and return up to count members with the lowest scores from the sorted set name.

For more information check https://redis.io/commands/zpopmin

zrandmember(key, count=None, withscores=False)[source]

Return a random element from the sorted set value stored at key.

count if the argument is positive, return an array of distinct fields. If called with a negative count, the behavior changes and the command is allowed to return the same field multiple times. In this case, the number of returned fields is the absolute value of the specified count.

withscores The optional WITHSCORES modifier changes the reply so it includes the respective scores of the randomly selected elements from the sorted set.

For more information check https://redis.io/commands/zrandmember

zrange(name, start, end, desc=False, withscores=False, score_cast_func=<class 'float'>, byscore=False, bylex=False, offset=None, num=None)[source]

Return a range of values from sorted set name between start and end sorted in ascending order.

start and end can be negative, indicating the end of the range.

desc a boolean indicating whether to sort the results in reversed order.

withscores indicates to return the scores along with the values. The return type is a list of (value, score) pairs.

score_cast_func a callable used to cast the score return value.

byscore when set to True, returns the range of elements from the sorted set having scores equal or between start and end.

bylex when set to True, returns the range of elements from the sorted set between the start and end lexicographical closed range intervals. Valid start and end must start with ( or [, in order to specify whether the range interval is exclusive or inclusive, respectively.

offset and num are specified, then return a slice of the range. Can’t be provided when using bylex.

For more information check https://redis.io/commands/zrange

zrangebylex(name, min, max, start=None, num=None)[source]

Return the lexicographical range of values from sorted set name between min and max.

If start and num are specified, then return a slice of the range.

For more information check https://redis.io/commands/zrangebylex

zrangebyscore(name, min, max, start=None, num=None, withscores=False, score_cast_func=<class 'float'>)[source]

Return a range of values from the sorted set name with scores between min and max.

If start and num are specified, then return a slice of the range.

withscores indicates to return the scores along with the values. The return type is a list of (value, score) pairs

score_cast_func` a callable used to cast the score return value

For more information check https://redis.io/commands/zrangebyscore

zrangestore(dest, name, start, end, byscore=False, bylex=False, desc=False, offset=None, num=None)[source]

Stores in dest the result of a range of values from sorted set name between start and end sorted in ascending order.

start and end can be negative, indicating the end of the range.

byscore when set to True, returns the range of elements from the sorted set having scores equal or between start and end.

bylex when set to True, returns the range of elements from the sorted set between the start and end lexicographical closed range intervals. Valid start and end must start with ( or [, in order to specify whether the range interval is exclusive or inclusive, respectively.

desc a boolean indicating whether to sort the results in reversed order.

offset and num are specified, then return a slice of the range. Can’t be provided when using bylex.

For more information check https://redis.io/commands/zrangestore

zrank(name, value)[source]

Returns a 0-based value indicating the rank of value in sorted set name

For more information check https://redis.io/commands/zrank

zrem(name, *values)[source]

Remove member values from sorted set name

For more information check https://redis.io/commands/zrem

zremrangebylex(name, min, max)[source]

Remove all elements in the sorted set name between the lexicographical range specified by min and max.

Returns the number of elements removed.

For more information check https://redis.io/commands/zremrangebylex

zremrangebyrank(name, min, max)[source]

Remove all elements in the sorted set name with ranks between min and max. Values are 0-based, ordered from smallest score to largest. Values can be negative indicating the highest scores. Returns the number of elements removed

For more information check https://redis.io/commands/zremrangebyrank

zremrangebyscore(name, min, max)[source]

Remove all elements in the sorted set name with scores between min and max. Returns the number of elements removed.

For more information check https://redis.io/commands/zremrangebyscore

zrevrange(name, start, end, withscores=False, score_cast_func=<class 'float'>)[source]

Return a range of values from sorted set name between start and end sorted in descending order.

start and end can be negative, indicating the end of the range.

withscores indicates to return the scores along with the values The return type is a list of (value, score) pairs

score_cast_func a callable used to cast the score return value

For more information check https://redis.io/commands/zrevrange

zrevrangebylex(name, max, min, start=None, num=None)[source]

Return the reversed lexicographical range of values from sorted set name between max and min.

If start and num are specified, then return a slice of the range.

For more information check https://redis.io/commands/zrevrangebylex

zrevrangebyscore(name, max, min, start=None, num=None, withscores=False, score_cast_func=<class 'float'>)[source]

Return a range of values from the sorted set name with scores between min and max in descending order.

If start and num are specified, then return a slice of the range.

withscores indicates to return the scores along with the values. The return type is a list of (value, score) pairs

score_cast_func a callable used to cast the score return value

For more information check https://redis.io/commands/zrevrangebyscore

zrevrank(name, value)[source]

Returns a 0-based value indicating the descending rank of value in sorted set name

For more information check https://redis.io/commands/zrevrank

zscan(name, cursor=0, match=None, count=None, score_cast_func=<class 'float'>)[source]

Incrementally return lists of elements in a sorted set. Also return a cursor indicating the scan position.

match allows for filtering the keys by pattern

count allows for hint the minimum number of returns

score_cast_func a callable used to cast the score return value

For more information check https://redis.io/commands/zscan

zscan_iter(name, match=None, count=None, score_cast_func=<class 'float'>)[source]

Make an iterator using the ZSCAN command so that the client doesn’t need to remember the cursor position.

match allows for filtering the keys by pattern

count allows for hint the minimum number of returns

score_cast_func a callable used to cast the score return value

zscore(name, value)[source]

Return the score of element value in sorted set name

For more information check https://redis.io/commands/zscore

zunion(keys, aggregate=None, withscores=False)[source]

Return the union of multiple sorted sets specified by keys. keys can be provided as dictionary of keys and their weights. Scores will be aggregated based on the aggregate, or SUM if none is provided.

For more information check https://redis.io/commands/zunion

zunionstore(dest, keys, aggregate=None)[source]

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.

For more information check https://redis.io/commands/zunionstore

class redis.commands.RedisModuleCommands[source]

This class contains the wrapper functions to bring supported redis modules into the command namepsace.

ft(index_name='idx')[source]

Access the search namespace, providing support for redis search.

json(encoder=<json.encoder.JSONEncoder object>, decoder=<json.decoder.JSONDecoder object>)[source]

Access the json namespace, providing support for redis json.

ts()[source]

Access the timeseries namespace, providing support for redis timeseries data.

class redis.commands.SentinelCommands[source]

A class containing the commands specific to redis sentinal. This class is to be used as a mixin.

sentinel(*args)[source]

Redis Sentinel’s SENTINEL command.

sentinel_ckquorum(new_master_name)[source]

Check if the current Sentinel configuration is able to reach the quorum needed to failover a master, and the majority needed to authorize the failover.

This command should be used in monitoring systems to check if a Sentinel deployment is ok.

sentinel_failover(new_master_name)[source]

Force a failover as if the master was not reachable, and without asking for agreement to other Sentinels (however a new version of the configuration will be published so that the other Sentinels will update their configurations).

sentinel_flushconfig()[source]

Force Sentinel to rewrite its configuration on disk, including the current Sentinel state.

Normally Sentinel rewrites the configuration every time something changes in its state (in the context of the subset of the state which is persisted on disk across restart). However sometimes it is possible that the configuration file is lost because of operation errors, disk failures, package upgrade scripts or configuration managers. In those cases a way to to force Sentinel to rewrite the configuration file is handy.

This command works even if the previous configuration file is completely missing.

sentinel_get_master_addr_by_name(service_name)[source]

Returns a (host, port) pair for the given service_name

sentinel_master(service_name)[source]

Returns a dictionary containing the specified masters state.

sentinel_masters()[source]

Returns a list of dictionaries containing each master’s state.

sentinel_monitor(name, ip, port, quorum)[source]

Add a new master to Sentinel to be monitored

sentinel_remove(name)[source]

Remove a master from Sentinel’s monitoring

sentinel_reset(pattern)[source]

This command will reset all the masters with matching name. The pattern argument is a glob-style pattern.

The reset process clears any previous state in a master (including a failover in progress), and removes every slave and sentinel already discovered and associated with the master.

sentinel_sentinels(service_name)[source]

Returns a list of sentinels for service_name

sentinel_set(name, option, value)[source]

Set Sentinel monitoring parameters for a given master

sentinel_slaves(service_name)[source]

Returns a list of slaves for service_name

Core exceptions raised by the Redis client

exception redis.exceptions.AuthenticationError[source]
exception redis.exceptions.AuthenticationWrongNumberOfArgsError[source]

An error to indicate that the wrong number of args were sent to the AUTH command

exception redis.exceptions.BusyLoadingError[source]
exception redis.exceptions.ChildDeadlockedError[source]

Error indicating that a child process is deadlocked after a fork()

exception redis.exceptions.ConnectionError[source]
exception redis.exceptions.DataError[source]
exception redis.exceptions.ExecAbortError[source]
exception redis.exceptions.InvalidResponse[source]
exception redis.exceptions.LockError[source]

Errors acquiring or releasing a lock

exception redis.exceptions.LockNotOwnedError[source]

Error trying to extend or release a lock that is (no longer) owned

exception redis.exceptions.ModuleError[source]
exception redis.exceptions.NoPermissionError[source]
exception redis.exceptions.NoScriptError[source]
exception redis.exceptions.PubSubError[source]
exception redis.exceptions.ReadOnlyError[source]
exception redis.exceptions.RedisError[source]
exception redis.exceptions.ResponseError[source]
exception redis.exceptions.TimeoutError[source]
exception redis.exceptions.WatchError[source]
class redis.lock.Lock(redis, name, timeout=None, sleep=0.1, blocking=True, blocking_timeout=None, thread_local=True)[source]

A shared, distributed Lock. Using Redis for locking allows the Lock to be shared across processes and/or machines.

It’s left to the user to resolve deadlock issues and make sure multiple clients play nicely together.

acquire(blocking=None, blocking_timeout=None, token=None)[source]

Use Redis to hold a shared, distributed lock named name. Returns True once the lock is acquired.

If blocking is False, always return immediately. If the lock was acquired, return True, otherwise return False.

blocking_timeout specifies the maximum number of seconds to wait trying to acquire the lock.

token specifies the token value to be used. If provided, token must be a bytes object or a string that can be encoded to a bytes object with the default encoding. If a token isn’t specified, a UUID will be generated.

extend(additional_time, replace_ttl=False)[source]

Adds more time to an already acquired lock.

additional_time can be specified as an integer or a float, both representing the number of seconds to add.

replace_ttl if False (the default), add additional_time to the lock’s existing ttl. If True, replace the lock’s ttl with additional_time.

locked()[source]

Returns True if this key is locked by any process, otherwise False.

owned()[source]

Returns True if this key is locked by this lock, otherwise False.

reacquire()[source]

Resets a TTL of an already acquired lock back to a timeout value.

release()[source]

Releases the already acquired lock

exception redis.sentinel.MasterNotFoundError[source]
class redis.sentinel.Sentinel(sentinels, min_other_sentinels=0, sentinel_kwargs=None, **connection_kwargs)[source]

Redis Sentinel cluster client

>>> from redis.sentinel import Sentinel
>>> sentinel = Sentinel([('localhost', 26379)], socket_timeout=0.1)
>>> master = sentinel.master_for('mymaster', socket_timeout=0.1)
>>> master.set('foo', 'bar')
>>> slave = sentinel.slave_for('mymaster', socket_timeout=0.1)
>>> slave.get('foo')
b'bar'

sentinels is a list of sentinel nodes. Each node is represented by a pair (hostname, port).

min_other_sentinels defined a minimum number of peers for a sentinel. When querying a sentinel, if it doesn’t meet this threshold, responses from that sentinel won’t be considered valid.

sentinel_kwargs is a dictionary of connection arguments used when connecting to sentinel instances. Any argument that can be passed to a normal Redis connection can be specified here. If sentinel_kwargs is not specified, any socket_timeout and socket_keepalive options specified in connection_kwargs will be used.

connection_kwargs are keyword arguments that will be used when establishing a connection to a Redis server.

discover_master(service_name)[source]

Asks sentinel servers for the Redis master’s address corresponding to the service labeled service_name.

Returns a pair (address, port) or raises MasterNotFoundError if no master is found.

discover_slaves(service_name)[source]

Returns a list of alive slaves for service service_name

execute_command(*args, **kwargs)[source]

Execute Sentinel command in sentinel nodes. once - If set to True, then execute the resulting command on a single

node at random, rather than across the entire sentinel cluster.
filter_slaves(slaves)[source]

Remove slaves that are in an ODOWN or SDOWN state

master_for(service_name, redis_class=<class 'redis.client.Redis'>, connection_pool_class=<class 'redis.sentinel.SentinelConnectionPool'>, **kwargs)[source]

Returns a redis client instance for the service_name master.

A SentinelConnectionPool class is used to retrieve the master’s address before establishing a new connection.

NOTE: If the master’s address has changed, any cached connections to the old master are closed.

By default clients will be a Redis instance. Specify a different class to the redis_class argument if you desire something different.

The connection_pool_class specifies the connection pool to use. The SentinelConnectionPool will be used by default.

All other keyword arguments are merged with any connection_kwargs passed to this class and passed to the connection pool as keyword arguments to be used to initialize Redis connections.

slave_for(service_name, redis_class=<class 'redis.client.Redis'>, connection_pool_class=<class 'redis.sentinel.SentinelConnectionPool'>, **kwargs)[source]

Returns redis client instance for the service_name slave(s).

A SentinelConnectionPool class is used to retrieve the slave’s address before establishing a new connection.

By default clients will be a Redis instance. Specify a different class to the redis_class argument if you desire something different.

The connection_pool_class specifies the connection pool to use. The SentinelConnectionPool will be used by default.

All other keyword arguments are merged with any connection_kwargs passed to this class and passed to the connection pool as keyword arguments to be used to initialize Redis connections.

class redis.sentinel.SentinelConnectionPool(service_name, sentinel_manager, **kwargs)[source]

Sentinel backed connection pool.

If check_connection flag is set to True, SentinelManagedConnection sends a PING command right after establishing the connection.

rotate_slaves()[source]

Round-robin slave balancer

class redis.sentinel.SentinelManagedConnection(**kwargs)[source]
connect()[source]

Connects to the Redis server if not already connected

read_response()[source]

Read the response from a previously sent command

class redis.sentinel.SentinelManagedSSLConnection(**kwargs)[source]
exception redis.sentinel.SlaveNotFoundError[source]