asyncio (PEP 3156) Redis support
npx @tessl/cli install tessl/pypi-aioredis@2.0.0An asyncio-compatible Redis client built on top of asyncio that provides async/await support for all Redis operations. aioredis offers complete Redis protocol compatibility while maintaining familiar redis-py patterns in an async context, supporting connection pooling, pub/sub messaging, Redis Streams, distributed locking, and high-availability configurations with Redis Sentinel.
pip install aioredisimport aioredisCommon usage patterns:
from aioredis import Redis, from_url
from aioredis.connection import ConnectionPool
from aioredis.exceptions import (
RedisError, ConnectionError, TimeoutError, AuthenticationError,
BusyLoadingError, InvalidResponse, ResponseError, DataError,
PubSubError, WatchError, ReadOnlyError, LockError, LockNotOwnedError
)import asyncio
import aioredis
async def main():
# Create Redis client
redis = aioredis.Redis(host='localhost', port=6379, decode_responses=True)
# Basic string operations
await redis.set('key1', 'Hello World')
value = await redis.get('key1')
print(value) # "Hello World"
# Working with data structures
await redis.lpush('mylist', 'item1', 'item2', 'item3')
items = await redis.lrange('mylist', 0, -1)
print(items) # ['item3', 'item2', 'item1']
# Using connection pools
pool = aioredis.ConnectionPool.from_url("redis://localhost:6379")
redis_pool = aioredis.Redis(connection_pool=pool)
await redis_pool.set('pooled_key', 'pooled_value')
# Cleanup connections
await redis.aclose()
await pool.disconnect()
# Run the async function
asyncio.run(main())aioredis follows the Redis protocol specification and provides three main architectural layers:
Redis class that provides high-level async methods for all Redis commandsConnection, SSLConnection, UnixDomainSocketConnection) managing protocol communicationConnectionPool, BlockingConnectionPool) for efficient connection managementThe client maintains full compatibility with redis-py patterns while providing async/await interfaces. All Redis data types, commands, and advanced features are supported including transactions, pipelines, pub/sub, streams, and Lua scripting.
Core Redis operations for strings, numeric values, and key management. Includes fundamental commands like GET/SET, increment/decrement operations, key expiration, and pattern matching.
async def get(name: str) -> Optional[str]: ...
async def set(name: str, value: Any, ex: Optional[int] = None, px: Optional[int] = None, nx: bool = False, xx: bool = False) -> bool: ...
async def incr(name: str, amount: int = 1) -> int: ...
async def delete(*names: str) -> int: ...
async def exists(*names: str) -> int: ...
async def expire(name: str, time: int) -> bool: ...
async def keys(pattern: str = "*") -> List[str]: ...Redis data structure operations for lists, sets, hashes, sorted sets, streams, and HyperLogLog. Provides comprehensive async interfaces for all Redis collection types with full feature support.
async def lpush(name: str, *values: Any) -> int: ...
async def lrange(name: str, start: int, end: int) -> List[str]: ...
async def sadd(name: str, *values: Any) -> int: ...
async def smembers(name: str) -> Set[str]: ...
async def hset(name: str, mapping: Dict[str, Any]) -> int: ...
async def hgetall(name: str) -> Dict[str, str]: ...
async def zadd(name: str, mapping: Dict[str, float]) -> int: ...
async def zrange(name: str, start: int, end: int, withscores: bool = False) -> List: ...Advanced Redis functionality including pub/sub messaging, Redis Streams, transactions, pipelines, Lua scripting, and batch operations for high-performance applications.
def pipeline(transaction: bool = True) -> Pipeline: ...
def pubsub() -> PubSub: ...
async def publish(channel: str, message: str) -> int: ...
async def xadd(name: str, fields: Dict[str, Any], id: str = "*") -> str: ...
async def eval(script: str, numkeys: int, *keys_and_args: Any) -> Any: ...
def lock(name: str, timeout: Optional[float] = None) -> Lock: ...Connection and pooling functionality for managing Redis connections, including URL-based configuration, SSL connections, Unix sockets, and connection pool optimization.
class Redis:
def __init__(
self,
host: str = "localhost",
port: int = 6379,
db: int = 0,
password: Optional[str] = None,
connection_pool: Optional[ConnectionPool] = None,
**kwargs
): ...
@classmethod
def from_url(cls, url: str, **kwargs) -> "Redis": ...
class ConnectionPool:
def __init__(self, max_connections: int = 50, **connection_kwargs): ...
@classmethod
def from_url(cls, url: str, **kwargs) -> "ConnectionPool": ...Server management commands for Redis administration including configuration, monitoring, persistence control, replication, and cluster operations.
async def info(section: Optional[str] = None) -> Dict[str, Any]: ...
async def config_get(pattern: str = "*") -> Dict[str, str]: ...
async def config_set(name: str, value: str) -> bool: ...
async def save() -> bool: ...
async def flushdb() -> bool: ...
async def monitor() -> Monitor: ...from typing import Optional, Union, Dict, List, Set, Any, Awaitable, AsyncIterator
from asyncio import StreamReader, StreamWriter
# Basic type aliases
KeyT = Union[bytes, str, memoryview]
EncodableT = Union[bytes, str, memoryview, int, float]
ResponseCallbackT = Callable[[Any], Any]aioredis provides a comprehensive exception hierarchy for handling different types of Redis errors:
# Base exception
class RedisError(Exception):
"""Base exception for all Redis errors."""
# Connection-related exceptions
class ConnectionError(RedisError):
"""Connection establishment and communication errors."""
class TimeoutError(asyncio.TimeoutError, builtins.TimeoutError, RedisError):
"""Operation timeout errors."""
class AuthenticationError(ConnectionError):
"""Authentication failure errors."""
class AuthenticationWrongNumberOfArgsError(ResponseError):
"""Wrong number of arguments for AUTH command."""
class BusyLoadingError(ConnectionError):
"""Server busy loading from disk."""
# Protocol and response exceptions
class InvalidResponse(RedisError):
"""Invalid protocol response from server."""
class ResponseError(RedisError):
"""Redis server error responses."""
class DataError(RedisError):
"""Data validation and type errors."""
class ReadOnlyError(ResponseError):
"""Write operations on read-only server."""
class NoScriptError(ResponseError):
"""Lua script not found."""
class ExecAbortError(ResponseError):
"""Transaction aborted by server."""
class NoPermissionError(ResponseError):
"""Insufficient permissions for operation."""
class ModuleError(ResponseError):
"""Redis module errors."""
# Specialized exceptions
class PubSubError(RedisError):
"""Pub/Sub operation errors."""
class WatchError(RedisError):
"""WATCH command conflicts."""
# Lock exceptions
class LockError(RedisError, ValueError):
"""Distributed lock operation errors."""
class LockNotOwnedError(LockError):
"""Lock not owned by current client."""
# Process management
class ChildDeadlockedError(Exception):
"""Child process deadlock after fork."""