API reference
Client
- class redis_anyio.RedisClient(host='localhost', port=6379, *, db=0, ssl=False, username=None, password=None, pool_size=64, pool_overflow=2048, connect_timeout=10, retry_wait=<tenacity.wait.wait_exponential object>, retry_stop=<tenacity.stop._stop_never object>)
- async blmove(source, destination, wherefrom, whereto, *, timeout=0, decode=True)
Atomically move an element from one array to another.
Unlike
lmove(), this method first waits for an element to appear onsourceif it’s currently empty.- Parameters:
source (
str) – the source keydestination (
str) – the destination keywherefrom (
Literal['left','right']) – eitherleftorrightwhereto (
Literal['left','right']) – eitherleftorrighttimeout (
float) – seconds to wait for an element to appear onsource; 0 to wait indefinitelydecode (
bool) –Trueto decode byte strings in the response to strings,Falseto leave them as is
- Return type:
- Returns:
the element being popped from
sourceand moved todestination, orNoneif the timeout was reached
See also
- async blmpop(wherefrom, *keys, count=None, timeout=0, decode=True)
Remove and return one or more elements from one of the given lists.
Unlike
lmpop(), this method first waits for an element to appear on any of the lists if all of them are empty.- Parameters:
wherefrom (
Literal['left','right']) –leftto remove an element from the beginning of the list,rightto remove one from the endkeys (
str) – the lists to remove elements fromcount (
int|None) – the maximum number of elements to remove (omit to return the first element)timeout (
float) – seconds to wait for an element to appear onsource; 0 to wait indefinitelydecode (
bool) –Trueto decode byte strings in the response to strings,Falseto leave them as is
- Return type:
- Returns:
a tuple of (key, list of removed elements)
See also
- async blpop(*keys, timeout=0, decode=True)
Remove and return the first element from one of the given lists.
Unlike
lpop(), this method first waits for an element to appear on any of the lists if all of them are empty.- Parameters:
- Return type:
- Returns:
a tuple of (list name, the removed element), or
Noneif the timeout was reached
See also
- async brpop(*keys, timeout=0, decode=True)
Remove and return the last element from one of the given lists.
Unlike
rpop(), this method first waits for an element to appear on any of the lists if all of them are empty.- Parameters:
- Return type:
- Returns:
a tuple of (list name, the removed element), or
Noneif the timeout was reached
See also
- async delete(*keys)
Delete one or more keys in the database.
- Return type:
- Returns:
the number of keys that was removed.
See also
- async eval(script, keys, args, *, decode=True)
Run the given Lua script and return its result.
- Parameters:
- Return type:
Union[None,str,bytes,float,bool,VerbatimString,Decimal,List[ResponseValue],Set[ResponseValue],Dict[ResponseValue, ResponseValue]]- Returns:
the return value of the script
See also
- async evalsha(sha1, keys, args, *, decode=True)
Run a previously stored Lua script and return its result.
- Parameters:
- Return type:
Union[None,str,bytes,float,bool,VerbatimString,Decimal,List[ResponseValue],Set[ResponseValue],Dict[ResponseValue, ResponseValue]]- Returns:
the return value of the script
See also
- async execute_command(command, *args, decode=True)
Execute a command on the Redis server.
Argument values that are not already bytes will be first converted to strings, and then encoded to bytes using the UTF-8 encoding.
- Parameters:
- Return type:
Union[None,str,bytes,float,bool,VerbatimString,Decimal,List[ResponseValue],Set[ResponseValue],Dict[ResponseValue, ResponseValue]]- Returns:
the return value of the command
- Raises:
ConnectivityError – if there’s a connectivity problem (can’t connect to the server, connection prematurely closed, etc.)
ResponseError – if the server returns an error response
- async expiretime(key)
Return the expiration time of the given key as a UNIX timestamp (in seconds).
- Return type:
- Returns:
the expiration time as an UNIX timestamp (in seconds), or -1 if the key exists but has no associated expiration time, or -2 if the key doesn’t exist
See also
- async flushall(sync=True)
Clears all keys in all databases.
- Parameters:
sync (
bool) – ifTrue, flush the databases synchronously; ifFalse, flush them asynchronously.- Return type:
See also
- async flushdb(sync=True)
Clears all keys in the currently selected database.
- Parameters:
sync (
bool) – ifTrue, flush the database synchronously; ifFalse, flush it asynchronously.- Return type:
See also
- async get(key, *, decode=True)
Retrieve the value of a key.
- Parameters:
- Return type:
- Returns:
the value of the key, or
Noneif the key did not exist
See also
- async getrange(key, start, end, decode=True)
Return a substring of the string value stored at
key.- Parameters:
- Return type:
- Returns:
the substring
See also
- async hdel(key, field)
Delete a field in the given hash map.
- Parameters:
- Return type:
- Returns:
1 if the hash map contained the given field, or 0 if either the field or the hash map did not exist
See also
- async hexists(key, field)
Check if the given field exists in the given hash map.
- Parameters:
- Return type:
- Returns:
Trueif the hash map contains the given field,Falseif not
See also
- async hget(key, field, decode=True)
Retrieve the value of a field in a hash map stored at
key.- Parameters:
- Return type:
- Returns:
the key values, with
Noneas a placeholder for fields that didn’t exist
See also
- async hgetall(key, decode=True)
Retrieve all fields and their values from a hash map stored at
key.- Parameters:
- Return type:
- Returns:
a mapping of fields to their values, or an empty dict if the hash map did not exist
See also
- async hincrby(key, field, increment)
Increment the value of the specified field in the given hash map.
If the field does not exist already, it will be created, with
incrementas the value.- Parameters:
- Return type:
- Returns:
the value of the field after the increment operation
See also
- async hincrbyfloat(key, field, increment)
Increment the value of the specified field in the given hash map by a floating point value.
If the field does not exist already, it will be created, with
incrementas the value.
- async hkeys(key)
Return the keys present in the given hash map.
- Parameters:
key (
str) – the hash map- Return type:
- Returns:
the list of keys in the hash map, or an empty list if the hash map doesn’t exist
See also
- async hlen(key)
Return the number of keys present in the given hash map.
- Parameters:
key (
str) – the hash map- Return type:
- Returns:
the number of keys in the hash map, or 0 if the hash map doesn’t exist
See also
- async hmget(key, *fields, decode=True)
Retrieve the values of multiple fields in a hash stored at
key.- Parameters:
- Return type:
- Returns:
the key values, with
Noneas a placeholder for fields that didn’t exist
See also
- async hrandfield(key, count=None, *, withvalues=False, decode=True)
Retrieve the value(s) of one or more random fields in the given hash map.
- Parameters:
key (
str) – the hash mapcount (
int|None) – if given, the number of fields to fetch (can be negative; see the official documentation for details)withvalues (
bool) – ifTrue, return a mapping of random fields to their valuesdecode (
bool) –Trueto decode byte strings in field values to strings,Falseto leave them as is (applied only whencountis specified andwithvaluesisTrue)
- Return type:
str|bytes|list[str] |list[bytes] |Mapping[str,str] |Mapping[str,bytes] |None- Returns:
Noneif the hash map didn’t existIf no
countwas specified: the value of a random fieldIf no
countwas specified, ifcountwas not given; otherwise, a list of the fetched values
See also
- async hscan_iter(key, *, match=None, count, decode=True)
Iterate over the fields in the given hash map.
- Parameters:
- Return type:
AsyncIterator[tuple[str,str]] |AsyncIterator[tuple[str,bytes]]- Returns:
an async context manager yielding an async iterator yielding tuples of (field name, field value)
Usage:
async for field, value in client.hscan("hashmapname", match="patter*"): print(f"Found field: {field} = {value}")
See also
- async hset(key, values)
Set the specified field values in the given hash map.
- Parameters:
- Return type:
- Returns:
the number of fields that were added
Usage:
await client.hset("somekey", {"key1": value1, "key2": value2})
See also
- async keys(pattern)
Return the keys in the database matching the given pattern.
- Parameters:
pattern (
str) – the pattern to match against- Return type:
- Returns:
the list of keys in the database that match the pattern
See also
- async lindex(key, index, *, decode=True)
Return the element at index
indexin keykey.- Parameters:
- Return type:
- Returns:
the element at the specified index
See also
- async linsert(key, where, pivot, element)
Insert
elementto the listkeyeither before or afterpivot.- Parameters:
- Return type:
- Returns:
the length of the list after a successful operation; 0 if the key doesn’t exist, and -1 when the pivot wasn’t found
See also
- async llen(key)
Remove and return the first element(s) value of a key.
- Parameters:
key (
str) – the array whose length to measure- Return type:
- Returns:
the length of the array
See also
- async lmove(source, destination, wherefrom, whereto, *, decode=True)
Atomically move an element from one array to another.
- Parameters:
- Return type:
- Returns:
the element being popped from
sourceand moved todestination, orNoneifsourcewas empty
See also
- async lmpop(wherefrom, *keys, count=None, decode=True)
Remove and return one or more elements from one of the given lists.
- Parameters:
wherefrom (
Literal['left','right']) –leftto remove an element from the beginning of the list,rightto remove one from the endkeys (
str) – the lists to remove elements fromcount (
int|None) – the maximum number of elements to remove (omit to return the first element)decode (
bool) –Trueto decode byte strings in the response to strings,Falseto leave them as is
- Return type:
- Returns:
a tuple of (key, list of elements), or
Noneif no elements were removed
See also
- lock(name, *, lifetime=30000, extend_interval=None, retry_interval=1000)
Create a lock object bound to this client.
- Parameters:
name (
str) – unique name of the locklifetime (
int|timedelta) – the expiration time of the lock (in milliseconds or as a timedelta)extend_interval (
int|timedelta|None) – Wait this long until extending the expiration time of the lock (in milliseconds or as a timedelta). If omitted, extending happens 5 seconds before the expiration is due, or lifetime / 2 if the life time is under 10 seconds.retry_interval (
int|timedelta) – if the lock was already acquired by another client, wait this long until trying to reacquire it (in milliseconds or as a timedelta)
- Return type:
Usage:
async with client.lock("lockname", 30000): ...
Alternatively, you can share the lock object among multiple tasks:
from anyio import create_task_group async def task_function(lock): async with lock: ... lock = client.lock("lockname", 30000) async with create_task_group() as tg: for _ in range(5): tg.start_soon(task_function, lock)
- async lpop(key, count=None, *, decode=True)
Remove and return the first element(s) from a list.
- Parameters:
- Return type:
- Returns:
a list of removed elements (if
countwas specified)the removed element (if
countwas omitted)Nonewhen no element could be popped.
See also
- async mget(*keys, decode=True)
Retrieve the values of multiple key.
- Parameters:
- Return type:
- Returns:
the key values, with
Noneas a placeholder for keys that didn’t exist
See also
- async mset(values)
Set the values of multiple keys.
See also
- async pexpire(key, milliseconds, *, how=None)
Set the timeout of the given key (in milliseconds).
- Return type:
- Returns:
1 if the timeout was set, 0 if the key doesn’t exist or the operation was skipped due to the operation modified (
how)
See also
- async pexpireat(key, timestamp, *, how=None)
Set the expiration time of the given key as a UNIX timestamp (in milliseconds).
- Return type:
- Returns:
1 if the timeout was set, 0 if the key doesn’t exist or the operation was skipped due to the operation modified (
how)
See also
- async pexpiretime(key)
Return the expiration time of the given key as a UNIX timestamp (in milliseconds).
- Return type:
- Returns:
the expiration time as an UNIX timestamp (in milliseconds), or -1 if the key exists but has no associated expiration time, or -2 if the key doesn’t exist
See also
- pipeline()
Create a new command pipeline bound to this client.
See also
- Return type:
- psubscribe(*patterns, send_connection_state_changes=False, decode=True)
Subscribe to one or more topic patterns.
- Parameters:
send_connection_state_changes (
bool) – ifTrue, send messages about disconnects and reconnections in a specially named topic within the stream (see the publish/subscribe section of the documentation for further info)decode (
bool) – ifTrue, decode the messages into strings using the UTF-8 encoding. IfFalse, yield raw bytes instead.
- Return type:
Union[Subscription[str],Subscription[bytes]]
Usage:
async with client.psubscribe("chann*", "ch[aie]n?el") as subscription: async for topic, data in subscription: ... # Received data on <topic>
See also
- async pttl(key)
Return the remaining time to live of a key, in milliseconds.
- Return type:
- Returns:
the time to live, or -1 if the key exists but has no associated expiration time, or -2 if the key doesn’t exist
See also
- async publish(channel, message)
Publish a message to the given channel.
- Parameters:
- Return type:
- Returns:
the number of clients that received the message
See also
- async rpop(key, count=None, *, decode=True)
Remove and return the last element(s) from a list.
- Parameters:
- Return type:
- Returns:
a list of removed elements (if
countwas specified)the removed element (if
countwas omitted)Nonewhen no element could be popped.
See also
- async rpush(key, *values)
Insert the given values to the tail of the list stored at
key.- Parameters:
- Return type:
- Returns:
the length of the list after the operation
See also
- async rpushx(key, *values)
Insert the given values to the tail of the list stored at
key.Unlike
rpush(), this variant only inserts the values ifkeyalready exists and is a list.- Parameters:
- Return type:
- Returns:
the length of the list after the operation
See also
- async scan_iter(*, match=None, count=None, type_=None)
Iterate over the set of keys in the current database.
- Parameters:
- Return type:
- Returns:
an async context manager yielding an async iterator yielding keys
Usage:
async for key in client.scan(match="patter*"): print(f"Found key: {key}")
See also
- async script_flush(sync=True)
Flush the Lua script cache.
- async script_load(script)
Load the given Lua script into the scripts cache (without executing it).
- async set(key, value, *, nx=False, xx=False, get=False, ex=None, px=None, exat=None, pxat=None, keepttl=False, decode=True)
Set
keyto hold the stringvalue.If both
nxandxxareTrue, thenxsetting wins.If more than one of the
ex,px,exatandpxatsettings have been set, the order of preference isex>px>exat>pxat, soexwould win if they all were defined.- Parameters:
key (
str) – the key to setvalue (
object) – the value to set for the keynx (
bool) – ifTrue, only set the key if it doesn’t already existxx (
bool) – ifTrue, only set the key if it already existsex (
int|timedelta|None) – specified expire time, in secondspx (
int|timedelta|None) – specified expire time, in millisecondsexat (
int|datetime|None) – specified UNIX timestamp for expiration, in secondspxat (
int|datetime|None) – specified UNIX timestamp for expiration, in millisecondsget (
bool) – ifTrue, return the previous value of the keykeepttl (
bool) – ifTrue, retain the time to live associated with the keydecode (
bool) –Trueto decode byte strings in the response to strings,Falseto leave them as is
- Return type:
- Returns:
the previous value, if
get=True
See also
- async setrange(key, offset, value)
Overwrite part of the specific string key.
- Parameters:
- Return type:
- Returns:
the length of the string after the modification
Warning
Take care when modifying multibyte (outside of the ASCII range) strings, as each character may require more than one byte.
See also
- async spublish(shardchannel, message)
Publish a message to the given shard channel.
- Parameters:
- Return type:
- Returns:
the number of clients that received the message
See also
- ssubscribe(*shardchannels, send_connection_state_changes=False, decode=True)
Subscribe to one or more shard channels.
- Parameters:
send_connection_state_changes (
bool) – ifTrue, send messages about disconnects and reconnections in a specially named topic within the stream (see the publish/subscribe section of the documentation for further info)decode (
bool) – ifTrue, decode the messages into strings using the UTF-8 encoding. IfFalse, yield raw bytes instead.
- Return type:
Union[Subscription[str],Subscription[bytes]]
Usage:
async with client.ssubscribe("channel1", "channel2") as subscription: async for channel, data in subscription: ... # Received data on <channel>
See also
- statistics()
Return statistics for the connection pool.
- Return type:
- subscribe(*channels, send_connection_state_changes=False, decode=True)
Subscribe to one or more channels.
- Parameters:
send_connection_state_changes (
bool) – ifTrue, send messages about disconnects and reconnections in a specially named topic within the stream (see the publish/subscribe section of the documentation for further info)decode (
bool) – ifTrue, decode the messages into strings using the UTF-8 encoding. IfFalse, yield raw bytes instead.
- Return type:
Union[Subscription[str],Subscription[bytes]]
Usage:
async with client.subscribe("channel1", "channel2") as subscription: async for channel, data in subscription: ... # Received data on <channel>
See also
- async time()
Return the current server time.
- Return type:
- Returns:
a tuple of (UNIX timestamp in seconds, microseconds elapsed in the current second)
See also
- transaction()
Create a new transaction bound to this client.
A transaction is a pipeline with slightly different semantics. See the documentation of the
RedisTransactionclass for further details.See also
- Return type:
Types
- class redis_anyio.VerbatimString(type_: bytes, value: bytes)
A string with embedded formatting information.
- class redis_anyio.Subscription(pool, channels, subscribe_category, message_category, send_connection_state_changes, decode, subscribe_command, unsubscribe_command)
- class redis_anyio.Message(channel, message)
- class redis_anyio.RedisPipeline(pool)
- delete(*keys)
Queue a DELETE command.
See also
- Return type:
- flushall(sync=True)
Queue an FLUSHALL command.
See also
- Return type:
- flushdb(sync=True)
Queue an FLUSHDB command.
See also
- Return type:
- get(key, *, decode=True)
Queue a GET command.
See also
- Return type:
Union[QueuedCommand[str],QueuedCommand[bytes]]
- hset(key, values)
Queue an HSET command.
See also
- Return type:
- keys(pattern)
Queue a KEYS command.
See also
- Return type:
- pexpire(key, milliseconds, *, how=None)
Queue a PEXPIRE command.
See also
- Return type:
- pexpireat(key, timestamp, *, how=None)
Queue a PEXPIREAT command.
See also
- Return type:
- pexpiretime(key)
Queue a PEXPIRETIME command.
See also
- Return type:
- pttl(key)
Queue a PTTL command.
See also
- Return type:
- queue_command(command, *args, decode=True)
Queue an arbitrary command to be executed.
See also
- Return type:
- set(key, value, *, nx=False, xx=False, get=False, ex=None, px=None, exat=None, pxat=None, keepttl=False, decode=True)
Queue a SET command.
See also
- Return type:
Union[QueuedCommand[str|None],QueuedCommand[bytes|None]]
- class redis_anyio.RedisTransaction(pool)
Represents a Redis transaction.
This differs from
RedisPipelinein the following ways:- If any of the commands fails to be queued, the transaction is discarded
(using
DISCARD) and the response error is raised
The commands in the pipeline are wrapped with
MULTIandEXECcommands
- async execute()
Execute the commands queued thus far in a transaction.
- Raises:
ResponseError – if the server returns an error response when queuing one of the commands
- Return type:
- class redis_anyio.QueuedCommand(command, args, decode)
Represents a command queued in a pipeline or transaction.
- result
- The result of the command, once the pipeline or transaction has been executed.
- class redis_anyio.RedisConnectionPoolStatistics(max_connections, total_connections, idle_connections, busy_connections)
- class redis_anyio.RedisLock(name, lifetime, extend_interval, retry_interval, client)
Constants
- redis_anyio.CONNECTION_STATE_CHANNEL = '_connection_state'
str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.
- redis_anyio.DISCONNECTED = 'disconnected'
str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.
- redis_anyio.RECONNECTED = 'reconnected'
str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.
Exceptions
- exception redis_anyio.RedisError
Base class for all Redis related errors.
- exception redis_anyio.ResponseError(code, message)
Raised when the server responds to a command with an error.
- exception redis_anyio.ConnectivityError
Raised when an operation fails due to a non-retryable server connectivity error.
- exception redis_anyio.ProtocolError
Raised when there’s a problem decoding incoming data from the server.