aioredis.Redis — Commands Mixins Reference

This section contains reference for mixins implementing Redis commands.

Descriptions are taken from docstrings so may not contain proper markup.

class aioredis.Redis(pool_or_conn)

High-level Redis interface.

Gathers in one place Redis commands implemented in mixins.

For commands details see: http://redis.io/commands/#connection

Parameters

pool_or_conn (AbcConnection) – Can be either RedisConnection or ConnectionsPool.

property address

Redis connection address (if applicable).

auth(password)

Authenticate to server.

This method wraps call to aioredis.RedisConnection.auth()

close()

Close client connections.

property closed

True if connection is closed.

property connection

Either aioredis.RedisConnection, or aioredis.ConnectionsPool instance.

property db

Currently selected db index.

echo(message, *, encoding=<object object>)

Echo the given string.

property encoding

Current set codec or None.

property in_transaction

Set to True when MULTI command was issued.

ping(message=<object object>, *, encoding=<object object>)

Ping the server.

Accept optional echo message.

quit()

Close the connection.

select(db)

Change the selected database.

Generic commands

class aioredis.commands.GenericCommandsMixin

Generic commands mixin.

For commands details see: http://redis.io/commands/#generic

delete(key, *keys)

Delete a key.

dump(key)

Dump a key.

exists(key, *keys)

Check if key(s) exists.

Changed in version v0.2.9: Accept multiple keys; return type changed from bool to int.

expire(key, timeout)

Set a timeout on key.

if timeout is float it will be multiplied by 1000 coerced to int and passed to pexpire method.

Otherwise raises TypeError if timeout argument is not int.

expireat(key, timestamp)

Set expire timestamp on a key.

if timeout is float it will be multiplied by 1000 coerced to int and passed to pexpireat method.

Otherwise raises TypeError if timestamp argument is not int.

iscan(*, match=None, count=None)

Incrementally iterate the keys space using async for.

Usage example:

>>> async for key in redis.iscan(match='something*'):
...     print('Matched:', key)
keys(pattern, *, encoding=<object object>)

Returns all keys matching pattern.

migrate(host, port, key, dest_db, timeout, *, copy=False, replace=False)

Atomically transfer a key from a Redis instance to another one.

migrate_keys(host, port, keys, dest_db, timeout, *, copy=False, replace=False)

Atomically transfer keys from one Redis instance to another one.

Keys argument must be list/tuple of keys to migrate.

move(key, db)

Move key from currently selected database to specified destination.

Raises
object_encoding(key)

Returns the kind of internal representation used in order to store the value associated with a key (OBJECT ENCODING).

object_idletime(key)

Returns the number of seconds since the object is not requested by read or write operations (OBJECT IDLETIME).

object_refcount(key)

Returns the number of references of the value associated with the specified key (OBJECT REFCOUNT).

persist(key)

Remove the existing timeout on key.

pexpire(key, timeout)

Set a milliseconds timeout on key.

Raises

TypeError – if timeout is not int

pexpireat(key, timestamp)

Set expire timestamp on key, timestamp in milliseconds.

Raises

TypeError – if timeout is not int

pttl(key)

Returns time-to-live for a key, in milliseconds.

Special return values (starting with Redis 2.8):

  • command returns -2 if the key does not exist.

  • command returns -1 if the key exists but has no associated expire.

randomkey(*, encoding=<object object>)

Return a random key from the currently selected database.

rename(key, newkey)

Renames key to newkey.

Raises

ValueError – if key == newkey

renamenx(key, newkey)

Renames key to newkey only if newkey does not exist.

Raises

ValueError – if key == newkey

restore(key, ttl, value)

Creates a key associated with a value that is obtained via DUMP.

scan(cursor=0, match=None, count=None)

Incrementally iterate the keys space.

Usage example:

>>> match = 'something*'
>>> cur = b'0'
>>> while cur:
...     cur, keys = await redis.scan(cur, match=match)
...     for key in keys:
...         print('Matched:', key)
sort(key, *get_patterns, by=None, offset=None, count=None, asc=None, alpha=False, store=None)

Sort the elements in a list, set or sorted set.

touch(key, *keys)

Alters the last access time of a key(s).

Returns the number of keys that were touched.

ttl(key)

Returns time-to-live for a key, in seconds.

Special return values (starting with Redis 2.8): * command returns -2 if the key does not exist. * command returns -1 if the key exists but has no associated expire.

type(key)

Returns the string representation of the value’s type stored at key.

Delete a key asynchronously in another thread.

wait(numslaves, timeout)

Wait for the synchronous replication of all the write commands sent in the context of the current connection.

Geo commands

New in version v0.3.0.

class aioredis.commands.GeoCommandsMixin

Geo commands mixin.

For commands details see: http://redis.io/commands#geo

geoadd(key, longitude, latitude, member, *args, **kwargs)

Add one or more geospatial items in the geospatial index represented using a sorted set.

Return type

int

geodist(key, member1, member2, unit='m')

Returns the distance between two members of a geospatial index.

Return type

list[float or None]

geohash(key, member, *members, **kwargs)

Returns members of a geospatial index as standard geohash strings.

Return type

list[str or bytes or None]

geopos(key, member, *members, **kwargs)

Returns longitude and latitude of members of a geospatial index.

Return type

list[GeoPoint or None]

georadius(key, longitude, latitude, radius, unit='m', *, with_dist=False, with_hash=False, with_coord=False, count=None, sort=None, encoding=<object object>)

Query a sorted set representing a geospatial index to fetch members matching a given maximum distance from a point.

Return value follows Redis convention:

  • if none of WITH* flags are set – list of strings returned:

    >>> await redis.georadius('Sicily', 15, 37, 200, 'km')
    [b"Palermo", b"Catania"]
    
  • if any flag (or all) is set – list of named tuples returned:

    >>> await redis.georadius('Sicily', 15, 37, 200, 'km',
    ...                       with_dist=True)
    [GeoMember(name=b"Palermo", dist=190.4424, hash=None, coord=None),
     GeoMember(name=b"Catania", dist=56.4413, hash=None, coord=None)]
    
Raises
Return type

list[str] or list[GeoMember]

georadiusbymember(key, member, radius, unit='m', *, with_dist=False, with_hash=False, with_coord=False, count=None, sort=None, encoding=<object object>)

Query a sorted set representing a geospatial index to fetch members matching a given maximum distance from a member.

Return value follows Redis convention:

  • if none of WITH* flags are set – list of strings returned:

    >>> await redis.georadiusbymember('Sicily', 'Palermo', 200, 'km')
    [b"Palermo", b"Catania"]
    
  • if any flag (or all) is set – list of named tuples returned:

    >>> await redis.georadiusbymember('Sicily', 'Palermo', 200, 'km',
    ...                               with_dist=True)
    [GeoMember(name=b"Palermo", dist=190.4424, hash=None, coord=None),
     GeoMember(name=b"Catania", dist=56.4413, hash=None, coord=None)]
    
Raises
Return type

list[str] or list[GeoMember]

Geo commands result wrappers

class aioredis.commands.GeoPoint(longitude, latitude)

Bases: tuple

Named tuple representing result returned by GEOPOS and GEORADIUS commands.

Parameters
  • longitude (float) – longitude value.

  • latitude (float) – latitude value.

class aioredis.commands.GeoMember(member, dist, hash, coord)

Bases: tuple

Named tuple representing result returned by GEORADIUS and GEORADIUSBYMEMBER commands.

Parameters
  • member (str or bytes) – Value of geo sorted set item;

  • dist (None or float) – Distance in units passed to call. None if with_dist was not set in georadius() call.

  • hash (None or int) – Geo-hash represented as number. None if with_hash was not in georadius() call.

  • coord (None or GeoPoint) – Coordinate of geospatial index member. None if with_coord was not set in georadius() call.

Strings commands

class aioredis.commands.StringCommandsMixin

String commands mixin.

For commands details see: http://redis.io/commands/#string

append(key, value)

Append a value to key.

bitcount(key, start=None, end=None)

Count set bits in a string.

Raises

TypeError – if only start or end specified.

bitop_and(dest, key, *keys)

Perform bitwise AND operations between strings.

bitop_not(dest, key)

Perform bitwise NOT operations between strings.

bitop_or(dest, key, *keys)

Perform bitwise OR operations between strings.

bitop_xor(dest, key, *keys)

Perform bitwise XOR operations between strings.

bitpos(key, bit, start=None, end=None)

Find first bit set or clear in a string.

Raises

ValueError – if bit is not 0 or 1

decr(key)

Decrement the integer value of a key by one.

decrby(key, decrement)

Decrement the integer value of a key by the given number.

Raises

TypeError – if decrement is not int

get(key, *, encoding=<object object>)

Get the value of a key.

getbit(key, offset)

Returns the bit value at offset in the string value stored at key.

Raises
getrange(key, start, end, *, encoding=<object object>)

Get a substring of the string stored at a key.

Raises

TypeError – if start or end is not int

getset(key, value, *, encoding=<object object>)

Set the string value of a key and return its old value.

incr(key)

Increment the integer value of a key by one.

incrby(key, increment)

Increment the integer value of a key by the given amount.

Raises

TypeError – if increment is not int

incrbyfloat(key, increment)

Increment the float value of a key by the given amount.

Raises

TypeError – if increment is not int

mget(key, *keys, encoding=<object object>)

Get the values of all the given keys.

mset(*args)

Set multiple keys to multiple values or unpack dict to keys & values.

Raises
  • TypeError – if len of args is not event number

  • TypeError – if len of args equals 1 and it is not a dict

msetnx(key, value, *pairs)

Set multiple keys to multiple values, only if none of the keys exist.

Raises

TypeError – if len of pairs is not event number

psetex(key, milliseconds, value)

Set the value and expiration in milliseconds of a key.

Raises

TypeError – if milliseconds is not int

set(key, value, *, expire=0, pexpire=0, exist=None)

Set the string value of a key.

Raises

TypeError – if expire or pexpire is not int

setbit(key, offset, value)

Sets or clears the bit at offset in the string value stored at key.

Raises
  • TypeError – if offset is not int

  • ValueError – if offset is less than 0 or value is not 0 or 1

setex(key, seconds, value)

Set the value and expiration of a key.

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

Raises

TypeError – if seconds is neither int nor float

setnx(key, value)

Set the value of a key, only if the key does not exist.

setrange(key, offset, value)

Overwrite part of a string at key starting at the specified offset.

Raises
strlen(key)

Get the length of the value stored in a key.

Hash commands

class aioredis.commands.HashCommandsMixin

Hash commands mixin.

For commands details see: http://redis.io/commands#hash

hdel(key, field, *fields)

Delete one or more hash fields.

hexists(key, field)

Determine if hash field exists.

hget(key, field, *, encoding=<object object>)

Get the value of a hash field.

hgetall(key, *, encoding=<object object>)

Get all the fields and values in a hash.

hincrby(key, field, increment=1)

Increment the integer value of a hash field by the given number.

hincrbyfloat(key, field, increment=1.0)

Increment the float value of a hash field by the given number.

hkeys(key, *, encoding=<object object>)

Get all the fields in a hash.

hlen(key)

Get the number of fields in a hash.

hmget(key, field, *fields, encoding=<object object>)

Get the values of all the given fields.

hmset(key, field, value, *pairs)

Set multiple hash fields to multiple values.

hmset_dict(key, *args, **kwargs)

Set multiple hash fields to multiple values.

dict can be passed as first positional argument:

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

or keyword arguments can be used:

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

or dict argument can be mixed with kwargs:

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

Note

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

>>> await redis.hmset_dict('key', {'foo': 'bar'}, foo='baz')
>>> await redis.hget('key', 'foo', encoding='utf-8')
'baz'
hscan(key, cursor=0, match=None, count=None)

Incrementally iterate hash fields and associated values.

hset(key, field, value)

Set the string value of a hash field.

hsetnx(key, field, value)

Set the value of a hash field, only if the field does not exist.

hstrlen(key, field)

Get the length of the value of a hash field.

hvals(key, *, encoding=<object object>)

Get all the values in a hash.

ihscan(key, *, match=None, count=None)

Incrementally iterate sorted set items using async for.

Usage example:

>>> async for name, val in redis.ihscan(key, match='something*'):
...     print('Matched:', name, '->', val)

List commands

class aioredis.commands.ListCommandsMixin

List commands mixin.

For commands details see: http://redis.io/commands#list

blpop(key, *keys, timeout=0, encoding=<object object>)

Remove and get the first element in a list, or block until one is available.

Raises
brpop(key, *keys, timeout=0, encoding=<object object>)

Remove and get the last element in a list, or block until one is available.

Raises
brpoplpush(sourcekey, destkey, timeout=0, encoding=<object object>)

Remove and get the last element in a list, or block until one is available.

Raises
lindex(key, index, *, encoding=<object object>)

Get an element from a list by its index.

Raises

TypeError – if index is not int

linsert(key, pivot, value, before=False)

Inserts value in the list stored at key either before or after the reference value pivot.

llen(key)

Returns the length of the list stored at key.

lpop(key, *, encoding=<object object>)

Removes and returns the first element of the list stored at key.

lpush(key, value, *values)

Insert all the specified values at the head of the list stored at key.

lpushx(key, value)

Inserts value at the head of the list stored at key, only if key already exists and holds a list.

lrange(key, start, stop, *, encoding=<object object>)

Returns the specified elements of the list stored at key.

Raises

TypeError – if start or stop is not int

lrem(key, count, value)

Removes the first count occurrences of elements equal to value from the list stored at key.

Raises

TypeError – if count is not int

lset(key, index, value)

Sets the list element at index to value.

Raises

TypeError – if index is not int

ltrim(key, start, stop)

Trim an existing list so that it will contain only the specified range of elements specified.

Raises

TypeError – if start or stop is not int

rpop(key, *, encoding=<object object>)

Removes and returns the last element of the list stored at key.

rpoplpush(sourcekey, destkey, *, encoding=<object object>)

Atomically returns and removes the last element (tail) of the list stored at source, and pushes the element at the first element (head) of the list stored at destination.

rpush(key, value, *values)

Insert all the specified values at the tail of the list stored at key.

rpushx(key, value)

Inserts value at the tail of the list stored at key, only if key already exists and holds a list.

Set commands

class aioredis.commands.SetCommandsMixin

Set commands mixin.

For commands details see: http://redis.io/commands#set

isscan(key, *, match=None, count=None)

Incrementally iterate set elements using async for.

Usage example:

>>> async for val in redis.isscan(key, match='something*'):
...     print('Matched:', val)
sadd(key, member, *members)

Add one or more members to a set.

scard(key)

Get the number of members in a set.

sdiff(key, *keys)

Subtract multiple sets.

sdiffstore(destkey, key, *keys)

Subtract multiple sets and store the resulting set in a key.

sinter(key, *keys)

Intersect multiple sets.

sinterstore(destkey, key, *keys)

Intersect multiple sets and store the resulting set in a key.

sismember(key, member)

Determine if a given value is a member of a set.

smembers(key, *, encoding=<object object>)

Get all the members in a set.

smove(sourcekey, destkey, member)

Move a member from one set to another.

spop(key, count=None, *, encoding=<object object>)

Remove and return one or multiple random members from a set.

srandmember(key, count=None, *, encoding=<object object>)

Get one or multiple random members from a set.

srem(key, member, *members)

Remove one or more members from a set.

sscan(key, cursor=0, match=None, count=None)

Incrementally iterate Set elements.

sunion(key, *keys)

Add multiple sets.

sunionstore(destkey, key, *keys)

Add multiple sets and store the resulting set in a key.

Sorted Set commands

class aioredis.commands.SortedSetCommandsMixin

Sorted Sets commands mixin.

For commands details see: http://redis.io/commands/#sorted_set

bzpopmax(key, *keys, timeout=0, encoding=<object object>)

Remove and get an element with the highest score in the sorted set, or block until one is available.

Raises
bzpopmin(key, *keys, timeout=0, encoding=<object object>)

Remove and get an element with the lowest score in the sorted set, or block until one is available.

Raises
izscan(key, *, match=None, count=None)

Incrementally iterate sorted set items using async for.

Usage example:

>>> async for val, score in redis.izscan(key, match='something*'):
...     print('Matched:', val, ':', score)
zadd(key, score, member, *pairs, exist=None, changed=False, incr=False)

Add one or more members to a sorted set or update its score.

Raises
zcard(key)

Get the number of members in a sorted set.

zcount(key, min=-inf, max=inf, *, exclude=None)

Count the members in a sorted set with scores within the given values.

Raises
zincrby(key, increment, member)

Increment the score of a member in a sorted set.

Raises

TypeError – increment is not float or int

zinterstore(destkey, key, *keys, with_weights=False, aggregate=None)

Intersect multiple sorted sets and store result in a new key.

Parameters

with_weights (bool) – when set to true each key must be a tuple in form of (key, weight)

zlexcount(key, min=b'-', max=b'+', include_min=True, include_max=True)

Count the number of members in a sorted set between a given lexicographical range.

Raises
zpopmax(key, count=None, *, encoding=<object object>)

Removes and returns up to count members with the highest scores in the sorted set stored at key.

Raises

TypeError – if count is not int

zpopmin(key, count=None, *, encoding=<object object>)

Removes and returns up to count members with the lowest scores in the sorted set stored at key.

Raises

TypeError – if count is not int

zrange(key, start=0, stop=-1, withscores=False, encoding=<object object>)

Return a range of members in a sorted set, by index.

Raises
zrangebylex(key, min=b'-', max=b'+', include_min=True, include_max=True, offset=None, count=None, encoding=<object object>)

Return a range of members in a sorted set, by lexicographical range.

Raises
zrangebyscore(key, min=-inf, max=inf, withscores=False, offset=None, count=None, *, exclude=None, encoding=<object object>)

Return a range of members in a sorted set, by score.

Raises
zrank(key, member)

Determine the index of a member in a sorted set.

zrem(key, member, *members)

Remove one or more members from a sorted set.

zremrangebylex(key, min=b'-', max=b'+', include_min=True, include_max=True)

Remove all members in a sorted set between the given lexicographical range.

Raises
zremrangebyrank(key, start, stop)

Remove all members in a sorted set within the given indexes.

Raises
zremrangebyscore(key, min=-inf, max=inf, *, exclude=None)

Remove all members in a sorted set within the given scores.

Raises

TypeError – if min or max is not int or float

zrevrange(key, start, stop, withscores=False, encoding=<object object>)

Return a range of members in a sorted set, by index, with scores ordered from high to low.

Raises

TypeError – if start or stop is not int

zrevrangebylex(key, min=b'-', max=b'+', include_min=True, include_max=True, offset=None, count=None, encoding=<object object>)

Return a range of members in a sorted set, by lexicographical range from high to low.

Raises
zrevrangebyscore(key, max=inf, min=-inf, *, exclude=None, withscores=False, offset=None, count=None, encoding=<object object>)

Return a range of members in a sorted set, by score, with scores ordered from high to low.

Raises
zrevrank(key, member)

Determine the index of a member in a sorted set, with scores ordered from high to low.

zscan(key, cursor=0, match=None, count=None)

Incrementally iterate sorted sets elements and associated scores.

zscore(key, member)

Get the score associated with the given member in a sorted set.

zunionstore(destkey, key, *keys, with_weights=False, aggregate=None)

Add multiple sorted sets and store result in a new key.

Server commands

class aioredis.commands.ServerCommandsMixin

Server commands mixin.

For commands details see: http://redis.io/commands/#server

bgrewriteaof()

Asynchronously rewrite the append-only file.

bgsave()

Asynchronously save the dataset to disk.

client_getname(encoding=<object object>)

Get the current connection name.

client_kill()

Kill the connection of a client.

Warning

Not Implemented

client_list()

Get the list of client connections.

Returns list of ClientInfo named tuples.

client_pause(timeout)

Stop processing commands from clients for timeout milliseconds.

Raises
client_setname(name)

Set the current connection name.

command()

Get array of Redis commands.

command_count()

Get total number of Redis commands.

command_getkeys(command, *args, encoding='utf-8')

Extract keys given a full Redis command.

command_info(command, *commands)

Get array of specific Redis command details.

config_get(parameter='*')

Get the value of a configuration parameter(s).

If called without argument will return all parameters.

Raises

TypeError – if parameter is not string

config_resetstat()

Reset the stats returned by INFO.

config_rewrite()

Rewrite the configuration file with the in memory configuration.

config_set(parameter, value)

Set a configuration parameter to the given value.

dbsize()

Return the number of keys in the selected database.

debug_object(key)

Get debugging information about a key.

debug_segfault(key)

Make the server crash.

debug_sleep(timeout)

Suspend connection for timeout seconds.

flushall(async_op=False)

Remove all keys from all databases.

Parameters

async_op – lets the entire dataset to be freed asynchronously. Defaults to False

flushdb(async_op=False)

Remove all keys from the current database.

Parameters

async_op – lets a single database to be freed asynchronously. Defaults to False

info(section='default')

Get information and statistics about the server.

If called without argument will return default set of sections. For available sections, see http://redis.io/commands/INFO

Raises

ValueError – if section is invalid

lastsave()

Get the UNIX time stamp of the last successful save to disk.

monitor()

Listen for all requests received by the server in real time.

Warning

Will not be implemented for now.

role()

Return the role of the server instance.

Returns named tuples describing role of the instance. For fields information see http://redis.io/commands/role#output-format

save()

Synchronously save the dataset to disk.

shutdown(save=None)

Synchronously save the dataset to disk and then shut down the server.

slaveof(host, port=None)

Make the server a slave of another instance, or promote it as master.

Calling slaveof(None) will send SLAVEOF NO ONE.

Changed in version v0.2.6: slaveof() form deprecated in favour of explicit slaveof(None).

slowlog_get(length=None)

Returns the Redis slow queries log.

slowlog_len()

Returns length of Redis slow queries log.

slowlog_reset()

Resets Redis slow queries log.

sync()

Redis-server internal command used for replication.

time()

Return current server time.

HyperLogLog commands

class aioredis.commands.HyperLogLogCommandsMixin

HyperLogLog commands mixin.

For commands details see: http://redis.io/commands#hyperloglog

pfadd(key, value, *values)

Adds the specified elements to the specified HyperLogLog.

pfcount(key, *keys)

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

pfmerge(destkey, sourcekey, *sourcekeys)

Merge N different HyperLogLogs into a single one.

Transaction commands

class aioredis.commands.TransactionsCommandsMixin

Transaction commands mixin.

For commands details see: http://redis.io/commands/#transactions

Transactions HOWTO:

>>> tr = redis.multi_exec()
>>> result_future1 = tr.incr('foo')
>>> result_future2 = tr.incr('bar')
>>> try:
...     result = await tr.execute()
... except MultiExecError:
...     pass    # check what happened
>>> result1 = await result_future1
>>> result2 = await result_future2
>>> assert result == [result1, result2]
multi_exec()

Returns MULTI/EXEC pipeline wrapper.

Usage:

>>> tr = redis.multi_exec()
>>> fut1 = tr.incr('foo')   # NO `await` as it will block forever!
>>> fut2 = tr.incr('bar')
>>> result = await tr.execute()
>>> result
[1, 1]
>>> await asyncio.gather(fut1, fut2)
[1, 1]
pipeline()

Returns Pipeline object to execute bulk of commands.

It is provided for convenience. Commands can be pipelined without it.

Example:

>>> pipe = redis.pipeline()
>>> fut1 = pipe.incr('foo') # NO `await` as it will block forever!
>>> fut2 = pipe.incr('bar')
>>> result = await pipe.execute()
>>> result
[1, 1]
>>> await asyncio.gather(fut1, fut2)
[1, 1]
>>> #
>>> # The same can be done without pipeline:
>>> #
>>> fut1 = redis.incr('foo')    # the 'INCRY foo' command already sent
>>> fut2 = redis.incr('bar')
>>> await asyncio.gather(fut1, fut2)
[2, 2]
unwatch()

Forget about all watched keys.

watch(key, *keys)

Watch the given keys to determine execution of the MULTI/EXEC block.

class aioredis.commands.Pipeline(connection, commands_factory=lambda conn: conn, *, loop=None)

Commands pipeline.

Buffers commands for execution in bulk.

This class implements __getattr__ method allowing to call methods on instance created with commands_factory.

Parameters
coroutine execute(*, return_exceptions=False)

Executes all buffered commands and returns result.

Any exception that is raised by any command is caught and raised later when processing results.

If return_exceptions is set to True then all collected errors are returned in resulting list otherwise single aioredis.PipelineError exception is raised (containing all collected errors).

Parameters

return_exceptions (bool) – Raise or return exceptions.

Raises

aioredis.PipelineError – Raised when any command caused error.

class aioredis.commands.MultiExec(connection, commands_factory=lambda conn: conn, *, loop=None)

Bases: Pipeline.

Multi/Exec pipeline wrapper.

See Pipeline for parameters description.

coroutine execute(*, return_exceptions=False)

Executes all buffered commands and returns result.

see Pipeline.execute() for details.

Parameters

return_exceptions (bool) – Raise or return exceptions.

Raises

Scripting commands

class aioredis.commands.ScriptingCommandsMixin

Set commands mixin.

For commands details see: http://redis.io/commands#scripting

eval(script, keys=[], args=[])

Execute a Lua script server side.

evalsha(digest, keys=[], args=[])

Execute a Lua script server side by its SHA1 digest.

script_exists(digest, *digests)

Check existence of scripts in the script cache.

script_flush()

Remove all the scripts from the script cache.

script_kill()

Kill the script currently in execution.

script_load(script)

Load the specified Lua script into the script cache.

Server commands

class aioredis.commands.ServerCommandsMixin

Server commands mixin.

For commands details see: http://redis.io/commands/#server

bgrewriteaof()

Asynchronously rewrite the append-only file.

bgsave()

Asynchronously save the dataset to disk.

client_getname(encoding=<object object>)

Get the current connection name.

client_kill()

Kill the connection of a client.

Warning

Not Implemented

client_list()

Get the list of client connections.

Returns list of ClientInfo named tuples.

client_pause(timeout)

Stop processing commands from clients for timeout milliseconds.

Raises
client_setname(name)

Set the current connection name.

command()

Get array of Redis commands.

command_count()

Get total number of Redis commands.

command_getkeys(command, *args, encoding='utf-8')

Extract keys given a full Redis command.

command_info(command, *commands)

Get array of specific Redis command details.

config_get(parameter='*')

Get the value of a configuration parameter(s).

If called without argument will return all parameters.

Raises

TypeError – if parameter is not string

config_resetstat()

Reset the stats returned by INFO.

config_rewrite()

Rewrite the configuration file with the in memory configuration.

config_set(parameter, value)

Set a configuration parameter to the given value.

dbsize()

Return the number of keys in the selected database.

debug_object(key)

Get debugging information about a key.

debug_segfault(key)

Make the server crash.

debug_sleep(timeout)

Suspend connection for timeout seconds.

flushall(async_op=False)

Remove all keys from all databases.

Parameters

async_op – lets the entire dataset to be freed asynchronously. Defaults to False

flushdb(async_op=False)

Remove all keys from the current database.

Parameters

async_op – lets a single database to be freed asynchronously. Defaults to False

info(section='default')

Get information and statistics about the server.

If called without argument will return default set of sections. For available sections, see http://redis.io/commands/INFO

Raises

ValueError – if section is invalid

lastsave()

Get the UNIX time stamp of the last successful save to disk.

monitor()

Listen for all requests received by the server in real time.

Warning

Will not be implemented for now.

role()

Return the role of the server instance.

Returns named tuples describing role of the instance. For fields information see http://redis.io/commands/role#output-format

save()

Synchronously save the dataset to disk.

shutdown(save=None)

Synchronously save the dataset to disk and then shut down the server.

slaveof(host, port=None)

Make the server a slave of another instance, or promote it as master.

Calling slaveof(None) will send SLAVEOF NO ONE.

Changed in version v0.2.6: slaveof() form deprecated in favour of explicit slaveof(None).

slowlog_get(length=None)

Returns the Redis slow queries log.

slowlog_len()

Returns length of Redis slow queries log.

slowlog_reset()

Resets Redis slow queries log.

sync()

Redis-server internal command used for replication.

time()

Return current server time.

Pub/Sub commands

Also see aioredis.Channel.

class aioredis.commands.PubSubCommandsMixin

Pub/Sub commands mixin.

For commands details see: http://redis.io/commands/#pubsub

property channels

Returns read-only channels dict.

See pubsub_channels

property in_pubsub

Indicates that connection is in PUB/SUB mode.

Provides the number of subscribed channels.

property patterns

Returns read-only patterns dict.

See pubsub_patterns

psubscribe(pattern, *patterns)

Switch connection to Pub/Sub mode and subscribe to specified patterns.

Arguments can be instances of Channel.

Returns asyncio.gather() coroutine which when done will return a list of subscribed Channel objects with is_pattern property set to True.

publish(channel, message)

Post a message to channel.

publish_json(channel, obj)

Post a JSON-encoded message to channel.

pubsub_channels(pattern=None)

Lists the currently active channels.

pubsub_numpat()

Returns the number of subscriptions to patterns.

pubsub_numsub(*channels)

Returns the number of subscribers for the specified channels.

punsubscribe(pattern, *patterns)

Unsubscribe from specific patterns.

Arguments can be instances of Channel.

subscribe(channel, *channels)

Switch connection to Pub/Sub mode and subscribe to specified channels.

Arguments can be instances of Channel.

Returns asyncio.gather() coroutine which when done will return a list of Channel objects.

unsubscribe(channel, *channels)

Unsubscribe from specific channels.

Arguments can be instances of Channel.

Cluster commands

Warning

Current release (1.3.0) of the library does not support Redis Cluster in a full manner. It provides only several API methods which may be changed in future.

Streams commands

class aioredis.commands.StreamCommandsMixin

Stream commands mixin

Streams are available in Redis since v5.0

xack(stream, group_name, id, *ids)

Acknowledge a message for a given consumer group

xadd(stream, fields, message_id=b'*', max_len=None, exact_len=False)

Add a message to a stream.

xclaim(stream, group_name, consumer_name, min_idle_time, id, *ids)

Claim a message for a given consumer

xdel(stream, id)

Removes the specified entries(IDs) from a stream

xgroup_create(stream, group_name, latest_id='$', mkstream=False)

Create a consumer group

xgroup_delconsumer(stream, group_name, consumer_name)

Delete a specific consumer from a group

xgroup_destroy(stream, group_name)

Delete a consumer group

xgroup_setid(stream, group_name, latest_id='$')

Set the latest ID for a consumer group

xinfo(stream)

Retrieve information about the given stream.

An alias for xinfo_stream()

xinfo_consumers(stream, group_name)

Retrieve consumers of a consumer group

xinfo_groups(stream)

Retrieve the consumer groups for a stream

xinfo_help()

Retrieve help regarding the XINFO sub-commands

xinfo_stream(stream)

Retrieve information about the given stream.

xlen(stream)

Returns the number of entries inside a stream

xpending(stream, group_name, start=None, stop=None, count=None, consumer=None)

Get information on pending messages for a stream

Returned data will vary depending on the presence (or not) of the start/stop/count parameters. For more details see: https://redis.io/commands/xpending

Raises

ValueError – if the start/stop/count parameters are only partially specified

xrange(stream, start='-', stop='+', count=None)

Retrieve messages from a stream.

xread(streams, timeout=0, count=None, latest_ids=None)

Perform a blocking read on the given stream

Raises

ValueError – if the length of streams and latest_ids do not match

xread_group(group_name, consumer_name, streams, timeout=0, count=None, latest_ids=None, no_ack=False)

Perform a blocking read on the given stream as part of a consumer group

Raises

ValueError – if the length of streams and latest_ids do not match

xrevrange(stream, start='+', stop='-', count=None)

Retrieve messages from a stream in reverse order.

xtrim(stream, max_len, exact_len=False)

trims the stream to a given number of items, evicting older items