asyncio (PEP 3156) Redis support
npx @tessl/cli install tessl/pypi-aioredis@2.0.00
# aioredis
1
2
An 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.
3
4
## Package Information
5
6
- **Package Name**: aioredis
7
- **Language**: Python
8
- **Installation**: `pip install aioredis`
9
- **Version**: 2.0.1
10
11
## Core Imports
12
13
```python
14
import aioredis
15
```
16
17
Common usage patterns:
18
19
```python
20
from aioredis import Redis, from_url
21
from aioredis.connection import ConnectionPool
22
from aioredis.exceptions import (
23
RedisError, ConnectionError, TimeoutError, AuthenticationError,
24
BusyLoadingError, InvalidResponse, ResponseError, DataError,
25
PubSubError, WatchError, ReadOnlyError, LockError, LockNotOwnedError
26
)
27
```
28
29
## Basic Usage
30
31
```python
32
import asyncio
33
import aioredis
34
35
async def main():
36
# Create Redis client
37
redis = aioredis.Redis(host='localhost', port=6379, decode_responses=True)
38
39
# Basic string operations
40
await redis.set('key1', 'Hello World')
41
value = await redis.get('key1')
42
print(value) # "Hello World"
43
44
# Working with data structures
45
await redis.lpush('mylist', 'item1', 'item2', 'item3')
46
items = await redis.lrange('mylist', 0, -1)
47
print(items) # ['item3', 'item2', 'item1']
48
49
# Using connection pools
50
pool = aioredis.ConnectionPool.from_url("redis://localhost:6379")
51
redis_pool = aioredis.Redis(connection_pool=pool)
52
53
await redis_pool.set('pooled_key', 'pooled_value')
54
55
# Cleanup connections
56
await redis.aclose()
57
await pool.disconnect()
58
59
# Run the async function
60
asyncio.run(main())
61
```
62
63
## Architecture
64
65
aioredis follows the Redis protocol specification and provides three main architectural layers:
66
67
- **Client Layer**: The `Redis` class that provides high-level async methods for all Redis commands
68
- **Connection Layer**: Connection classes (`Connection`, `SSLConnection`, `UnixDomainSocketConnection`) managing protocol communication
69
- **Pool Layer**: Connection pooling (`ConnectionPool`, `BlockingConnectionPool`) for efficient connection management
70
71
The 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.
72
73
## Capabilities
74
75
### Basic Operations
76
77
Core Redis operations for strings, numeric values, and key management. Includes fundamental commands like GET/SET, increment/decrement operations, key expiration, and pattern matching.
78
79
```python { .api }
80
async def get(name: str) -> Optional[str]: ...
81
async def set(name: str, value: Any, ex: Optional[int] = None, px: Optional[int] = None, nx: bool = False, xx: bool = False) -> bool: ...
82
async def incr(name: str, amount: int = 1) -> int: ...
83
async def delete(*names: str) -> int: ...
84
async def exists(*names: str) -> int: ...
85
async def expire(name: str, time: int) -> bool: ...
86
async def keys(pattern: str = "*") -> List[str]: ...
87
```
88
89
[Basic Operations](./basic-operations.md)
90
91
### Data Structures
92
93
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.
94
95
```python { .api }
96
async def lpush(name: str, *values: Any) -> int: ...
97
async def lrange(name: str, start: int, end: int) -> List[str]: ...
98
async def sadd(name: str, *values: Any) -> int: ...
99
async def smembers(name: str) -> Set[str]: ...
100
async def hset(name: str, mapping: Dict[str, Any]) -> int: ...
101
async def hgetall(name: str) -> Dict[str, str]: ...
102
async def zadd(name: str, mapping: Dict[str, float]) -> int: ...
103
async def zrange(name: str, start: int, end: int, withscores: bool = False) -> List: ...
104
```
105
106
[Data Structures](./data-structures.md)
107
108
### Advanced Features
109
110
Advanced Redis functionality including pub/sub messaging, Redis Streams, transactions, pipelines, Lua scripting, and batch operations for high-performance applications.
111
112
```python { .api }
113
def pipeline(transaction: bool = True) -> Pipeline: ...
114
def pubsub() -> PubSub: ...
115
async def publish(channel: str, message: str) -> int: ...
116
async def xadd(name: str, fields: Dict[str, Any], id: str = "*") -> str: ...
117
async def eval(script: str, numkeys: int, *keys_and_args: Any) -> Any: ...
118
def lock(name: str, timeout: Optional[float] = None) -> Lock: ...
119
```
120
121
[Advanced Features](./advanced-features.md)
122
123
### Connection Management
124
125
Connection and pooling functionality for managing Redis connections, including URL-based configuration, SSL connections, Unix sockets, and connection pool optimization.
126
127
```python { .api }
128
class Redis:
129
def __init__(
130
self,
131
host: str = "localhost",
132
port: int = 6379,
133
db: int = 0,
134
password: Optional[str] = None,
135
connection_pool: Optional[ConnectionPool] = None,
136
**kwargs
137
): ...
138
139
@classmethod
140
def from_url(cls, url: str, **kwargs) -> "Redis": ...
141
142
class ConnectionPool:
143
def __init__(self, max_connections: int = 50, **connection_kwargs): ...
144
@classmethod
145
def from_url(cls, url: str, **kwargs) -> "ConnectionPool": ...
146
```
147
148
[Connection Management](./connection-management.md)
149
150
### Server Administration
151
152
Server management commands for Redis administration including configuration, monitoring, persistence control, replication, and cluster operations.
153
154
```python { .api }
155
async def info(section: Optional[str] = None) -> Dict[str, Any]: ...
156
async def config_get(pattern: str = "*") -> Dict[str, str]: ...
157
async def config_set(name: str, value: str) -> bool: ...
158
async def save() -> bool: ...
159
async def flushdb() -> bool: ...
160
async def monitor() -> Monitor: ...
161
```
162
163
[Server Administration](./server-admin.md)
164
165
## Core Types
166
167
```python { .api }
168
from typing import Optional, Union, Dict, List, Set, Any, Awaitable, AsyncIterator
169
from asyncio import StreamReader, StreamWriter
170
171
# Basic type aliases
172
KeyT = Union[bytes, str, memoryview]
173
EncodableT = Union[bytes, str, memoryview, int, float]
174
ResponseCallbackT = Callable[[Any], Any]
175
```
176
177
## Exception Hierarchy
178
179
aioredis provides a comprehensive exception hierarchy for handling different types of Redis errors:
180
181
```python { .api }
182
# Base exception
183
class RedisError(Exception):
184
"""Base exception for all Redis errors."""
185
186
# Connection-related exceptions
187
class ConnectionError(RedisError):
188
"""Connection establishment and communication errors."""
189
190
class TimeoutError(asyncio.TimeoutError, builtins.TimeoutError, RedisError):
191
"""Operation timeout errors."""
192
193
class AuthenticationError(ConnectionError):
194
"""Authentication failure errors."""
195
196
class AuthenticationWrongNumberOfArgsError(ResponseError):
197
"""Wrong number of arguments for AUTH command."""
198
199
class BusyLoadingError(ConnectionError):
200
"""Server busy loading from disk."""
201
202
# Protocol and response exceptions
203
class InvalidResponse(RedisError):
204
"""Invalid protocol response from server."""
205
206
class ResponseError(RedisError):
207
"""Redis server error responses."""
208
209
class DataError(RedisError):
210
"""Data validation and type errors."""
211
212
class ReadOnlyError(ResponseError):
213
"""Write operations on read-only server."""
214
215
class NoScriptError(ResponseError):
216
"""Lua script not found."""
217
218
class ExecAbortError(ResponseError):
219
"""Transaction aborted by server."""
220
221
class NoPermissionError(ResponseError):
222
"""Insufficient permissions for operation."""
223
224
class ModuleError(ResponseError):
225
"""Redis module errors."""
226
227
# Specialized exceptions
228
class PubSubError(RedisError):
229
"""Pub/Sub operation errors."""
230
231
class WatchError(RedisError):
232
"""WATCH command conflicts."""
233
234
# Lock exceptions
235
class LockError(RedisError, ValueError):
236
"""Distributed lock operation errors."""
237
238
class LockNotOwnedError(LockError):
239
"""Lock not owned by current client."""
240
241
# Process management
242
class ChildDeadlockedError(Exception):
243
"""Child process deadlock after fork."""
244
```