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, *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 key.
if timeout is float it will be multiplied by 1000 coerced to int and passed to pexpire 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.
-
move
(key, db)¶ Move key from currently selected database to specified destination.
Raises: - TypeError – if db is not int
- ValueError – if db is less then 0
-
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.
-
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.
-
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.
-
Python 3.5 async/await support¶
-
class
aioredis.commands.
GenericCommandsMixin
-
async-for
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)
See also
GenericCommandsMixin.scan()
.
-
async-for
Geo commands¶
-
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.
-
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, *args, **kwargs)¶ Returns members of a geospatial index as standard geohash strings.
-
geopos
(key, member, *args, **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: - TypeError – radius is not float or int
- TypeError – count is not int
- ValueError – if unit not equal
m
,km
,mi
orft
- ValueError – if sort not equal
ASC
orDESC
Return type:
-
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: - TypeError – radius is not float or int
- TypeError – count is not int
- ValueError – if unit not equal
m
,km
,mi
orft
- ValueError – if sort not equal
ASC
orDESC
Return type:
-
-
class
aioredis.commands.
GeoPoint
(longitude, latitude)¶
-
class
aioredis.commands.
GeoMember
(member, dist, hash, coord)¶
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: - TypeError – if offset is not int
- ValueError – if offset is less then 0
-
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
(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: - TypeError – if offset is not int
- ValueError – if offset less then 0
-
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
andkwargs
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)
-
Python 3.5 async/await support¶
-
class
aioredis.commands.
HashCommandsMixin
-
async-for
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)
See also
HashCommandsMixin.hscan()
.
-
async-for
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: - TypeError – if timeout is not int
- ValueError – if timeout is less then 0
-
brpop
(key, *keys, timeout=0, encoding=<object object>)¶ Remove and get the last element in a list, or block until one is available.
Raises: - TypeError – if timeout is not int
- ValueError – if timeout is less then 0
-
brpoplpush
(sourcekey, destkey, timeout=0, encoding=<object object>)¶ Remove and get the last element in a list, or block until one is available.
Raises: - TypeError – if timeout is not int
- ValueError – if timeout is less then 0
-
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, *, encoding=<object object>)¶ Remove and return a random member 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.
-
Python 3.5 async/await support¶
-
class
aioredis.commands.
SetCommandsMixin
-
async-for
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)
See also
SetCommandsMixin.sscan()
.
-
async-for
Sorted Set commands¶
-
class
aioredis.commands.
SortedSetCommandsMixin
¶ Sorted Sets commands mixin.
For commands details see: http://redis.io/commands/#sorted_set
-
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)¶ 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: - TypeError – min or max is not float or int
- ValueError – if min grater then max
-
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 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)¶ 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)¶ 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)¶ 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.
-
Python 3.5 async/await support¶
-
class
aioredis.commands.
SortedSetCommandsMixin
-
async-for
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)
See also
SortedSetCommandsMixin.zscan()
.
-
async-for
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: - TypeError – if timeout is not int
- ValueError – if timeout is less then 0
-
client_setname
(name)¶ Set the current connection name.
-
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.
-
flushall
()¶ Remove all keys from all databases.
-
flushdb
()¶ Remove all keys from the current database.
-
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=<object object>, port=None)¶ Make the server a slave of another instance, or promote it as master.
Calling
slaveof(None)
will sendSLAVEOF NO ONE
.Changed in version v0.2.6:
slaveof()
form deprecated in favour of explicitslaveof(None)
.
-
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 = 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: - connection (aioredis.RedisConnection) – Redis connection
- commands_factory (callable) – Commands factory to get methods from.
- loop (EventLoop) – An optional event loop instance
(uses
asyncio.get_event_loop()
if not specified).
-
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 toTrue
then all collected errors are returned in resulting list otherwise singleaioredis.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: - aioredis.MultiExecError – Raised instead of
aioredis.PipelineError
- aioredis.WatchVariableError – If watched variable is changed
- aioredis.MultiExecError – Raised instead of
-
coroutine
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: - TypeError – if timeout is not int
- ValueError – if timeout is less then 0
-
client_setname
(name) Set the current connection name.
-
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.
-
flushall
() Remove all keys from all databases.
-
flushdb
() Remove all keys from the current database.
-
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=<object object>, port=None) Make the server a slave of another instance, or promote it as master.
Calling
slaveof(None)
will sendSLAVEOF NO ONE
.Changed in version v0.2.6:
slaveof()
form deprecated in favour of explicitslaveof(None)
.
-
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.
-
Pub/Sub commands¶
Also see aioredis.Channel.
-
class
aioredis.commands.
PubSubCommandsMixin
¶ Pub/Sub commands mixin.
For commands details see: http://redis.io/commands/#pubsub
-
channels
¶ Returns read-only channels dict.
See
pubsub_channels
-
in_pubsub
¶ Indicates that connection is in PUB/SUB mode.
Provides the number of subscribed channels.
-
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 subscribedChannel
objects withis_pattern
property set toTrue
.
-
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 ofChannel
objects.
-
Cluster commands¶
Warning
Current release (0.3.4) of the library does not support Redis Cluster in a full manner. It provides only several API methods which may be changed in future.