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(connection)

High-level Redis interface.

Gathers in one place Redis commands implemented in mixins.

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

auth(password)

Authenticate to server.

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

closed

True if connection is closed.

connection

aioredis.RedisConnection instance.

db

Currently selected db index.

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

Echo the given string.

encoding

Current set codec or None.

in_transaction

Set to True when MULTI command was issued.

ping(*, encoding=<object object>)

Ping the server.

quit()

Close the connection.

select(db)

Change the selected database for the current connection.

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

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)

Check if key exists.

expire(key, timeout)

Set a timeout on key.

if timeout is float it will be multiplyed 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 key.

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

Otherwise raises TypeError if timestamp argument is not int.

keys(pattern)

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.

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()

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.

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.

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.

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)

Get a substring of the string stored at a key.

Raises TypeError:
 if start or end is not int
getset(key, value)

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)

Get the values of all the given keys.

mset(key, value, *pairs)

Set multiple keys to multiple values.

Raises TypeError:
 if len of pairs is not event number
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 then 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)

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)

Get all the fields in a hash.

hlen(key)

Get the number of fields in a hash.

hmget(key, field, *fields)

Get the values of all the given fields.

hmset(key, field, value, *pairs)

Set multiple hash fields to multiple values.

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.

hvals(key)

Get all the values in a hash.

List commands

class aioredis.commands.ListCommandsMixin

List commands mixin.

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

blpop(key, *keys, *, timeout=0)

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

Raises:
brpop(key, *keys, *, timeout=0)

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

Raises:
brpoplpush(sourcekey, destkey, timeout=0)

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

Raises:
lindex(key, index)

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)

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)

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)

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

rpoplpush(sourcekey, destkey)

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

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)

Get all the members in a set.

smove(sourcekey, destkey, member)

Move a member from one set to another.

spop(key)

Remove and return a random member from a set.

srandmember(key, count=None)

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

zadd(key, score, member, *pairs)

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:
zrange(key, start=0, stop=-1, withscores=False)

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)

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)

Return a range of memebers 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)

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
zrevrangebyscore(key, max=inf, min=-inf, *, exclude=None, withscores=False, offset=None, count=None)

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.

client_pause(timeout)

Stop processing commands from clients for timeout milliseconds.

Raises:
client_setname(name)

Set the current connection name.

config_get(parameter)

Get the value of a configuration parameter.

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.

flushall()

Remove all keys from all databases.

flushdb()

Remove all keys from the current database.

info(section)

Get information and statistics about the server.

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 instance in the context of replication.

save()

Synchronously save the dataset to disk.

shutdown(save=None)

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

slaveof(host=None, port=None)

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

Calling slaveof without arguments will send SLAVEOF NO ONE.

slowlog_get(length=None)

Returns the Redis slow queries log.

slowlog_len(length=None)

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 = yield from tr.execute()
... except MultiExecError:
...     pass    # check what happened
>>> result1 = yield from result_future1
>>> result2 = yield from result_future2
>>> assert result == [result1, result2]
multi_exec()

Returns MULTI/EXEC pipeline wrapper.

Usage:

>>> tr = redis.multi_exec()
>>> fut1 = tr.incr('foo')   # NO `yield from` as it will block forever!
>>> fut2 = tr.incr('bar')
>>> result = yield from tr.execute()
>>> result
[1, 1]
>>> yield from 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 `yield from` as it will block forever!
>>> fut2 = pipe.incr('bar')
>>> result = yield from pipe.execute()
>>> result
[1, 1]
>>> yield from 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')
>>> yield from 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:
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.

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 aioredis.MultiExecError:
 raised instead of aioredis.PipelineError

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.

client_pause(timeout)

Stop processing commands from clients for timeout milliseconds.

Raises:
client_setname(name)

Set the current connection name.

config_get(parameter)

Get the value of a configuration parameter.

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.

flushall()

Remove all keys from all databases.

flushdb()

Remove all keys from the current database.

info(section)

Get information and statistics about the server.

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 instance in the context of replication.

save()

Synchronously save the dataset to disk.

shutdown(save=None)

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

slaveof(host=None, port=None)

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

Calling slaveof without arguments will send SLAVEOF NO ONE.

slowlog_get(length=None)

Returns the Redis slow queries log.

slowlog_len(length=None)

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.