0
# Redis Python Client
1
2
A comprehensive Python client for Redis, the popular in-memory data structure store used as database, cache, and message broker. Provides both synchronous and asynchronous APIs with full support for Redis features including clustering, high availability, pub/sub messaging, transactions, pipelining, and Redis modules.
3
4
## Package Information
5
6
- **Package Name**: redis
7
- **Language**: Python
8
- **Installation**: `pip install redis`
9
- **Optional Dependencies**: `pip install "redis[hiredis]"` for improved performance
10
11
## Core Imports
12
13
```python
14
import redis
15
```
16
17
Common usage patterns:
18
19
```python
20
# Main Redis client
21
from redis import Redis
22
23
# Cluster client
24
from redis import RedisCluster
25
26
# Async clients
27
from redis.asyncio import Redis as AsyncRedis
28
from redis.asyncio import RedisCluster as AsyncRedisCluster
29
30
# High availability
31
from redis.sentinel import Sentinel
32
33
# Connection management
34
from redis import ConnectionPool, Connection
35
36
# Utilities
37
from redis import from_url
38
```
39
40
## Basic Usage
41
42
```python
43
import redis
44
45
# Connect to Redis server
46
r = redis.Redis(host='localhost', port=6379, db=0)
47
48
# Basic key-value operations
49
r.set('key', 'value')
50
value = r.get('key') # Returns b'value'
51
52
# Decoded strings (recommended)
53
r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
54
r.set('key', 'value')
55
value = r.get('key') # Returns 'value'
56
57
# Connection from URL
58
r = redis.from_url('redis://localhost:6379/0')
59
60
# Pipeline for batching commands
61
with r.pipeline() as pipe:
62
pipe.set('key1', 'value1')
63
pipe.set('key2', 'value2')
64
pipe.get('key1')
65
results = pipe.execute() # [True, True, 'value1']
66
67
# Pub/Sub messaging
68
pubsub = r.pubsub()
69
pubsub.subscribe('channel')
70
for message in pubsub.listen():
71
print(message)
72
```
73
74
## Architecture
75
76
The Redis client follows a modular architecture:
77
78
- **Client Layer**: Redis and RedisCluster classes providing the main API
79
- **Connection Layer**: Connection pools and connection management
80
- **Command Layer**: All Redis commands organized by functionality (strings, lists, sets, etc.)
81
- **Protocol Layer**: RESP protocol serialization and parsing
82
- **Async Layer**: Full async/await mirror of synchronous API
83
- **High Availability**: Sentinel support for automatic failover
84
- **Extensions**: Support for Redis modules (JSON, Search, TimeSeries, etc.)
85
86
## Capabilities
87
88
### Core Client
89
90
Main Redis client with full command support, connection pooling, and configuration options. Supports all Redis data types and operations including strings, lists, sets, hashes, streams, and geospatial commands.
91
92
```python { .api }
93
class Redis:
94
def __init__(
95
self,
96
host: str = "localhost",
97
port: int = 6379,
98
db: int = 0,
99
password: Optional[str] = None,
100
socket_timeout: Optional[float] = None,
101
decode_responses: bool = False,
102
**kwargs
103
): ...
104
105
@classmethod
106
def from_url(cls, url: str, **kwargs) -> "Redis": ...
107
108
def pipeline(self, transaction: bool = True) -> "Pipeline": ...
109
def pubsub(self, **kwargs) -> "PubSub": ...
110
def lock(self, name: str, timeout: Optional[float] = None) -> "Lock": ...
111
```
112
113
[Core Client](./core-client.md)
114
115
### Cluster Support
116
117
Redis Cluster client for distributed Redis deployments with automatic sharding and node discovery.
118
119
```python { .api }
120
class RedisCluster:
121
def __init__(
122
self,
123
host: Optional[str] = None,
124
port: int = 7000,
125
startup_nodes: Optional[List[ClusterNode]] = None,
126
**kwargs
127
): ...
128
129
@classmethod
130
def from_url(cls, url: str, **kwargs) -> "RedisCluster": ...
131
```
132
133
[Cluster Support](./cluster-support.md)
134
135
### Connection Management
136
137
Connection pools, connection types, and connection configuration for managing Redis connections efficiently.
138
139
```python { .api }
140
class ConnectionPool:
141
def __init__(
142
self,
143
connection_class: Type[Connection] = Connection,
144
max_connections: Optional[int] = None,
145
**connection_kwargs
146
): ...
147
148
class Connection:
149
def __init__(
150
self,
151
host: str = "localhost",
152
port: int = 6379,
153
db: int = 0,
154
**kwargs
155
): ...
156
```
157
158
[Connection Management](./connection-management.md)
159
160
### Async Support
161
162
Full asynchronous API using asyncio, providing async versions of all Redis operations with identical interfaces to synchronous clients.
163
164
```python { .api }
165
class Redis: # Async version
166
async def get(self, name: str) -> Optional[bytes]: ...
167
async def set(self, name: str, value: Any, **kwargs) -> bool: ...
168
def pipeline(self, transaction: bool = True) -> "Pipeline": ...
169
```
170
171
[Async Support](./async-support.md)
172
173
### High Availability (Sentinel)
174
175
Redis Sentinel integration for automatic master/slave discovery and failover in high availability deployments.
176
177
```python { .api }
178
class Sentinel:
179
def __init__(
180
self,
181
sentinels: List[Tuple[str, int]],
182
**kwargs
183
): ...
184
185
def master_for(self, service_name: str, **kwargs) -> Redis: ...
186
def slave_for(self, service_name: str, **kwargs) -> Redis: ...
187
```
188
189
[High Availability](./high-availability.md)
190
191
### Pipelines and Transactions
192
193
Command batching with pipelines and atomic transactions with MULTI/EXEC support, including optimistic locking with WATCH.
194
195
```python { .api }
196
class Pipeline:
197
def execute(self, raise_on_error: bool = True) -> List[Any]: ...
198
def watch(self, *names: str) -> bool: ...
199
def multi(self) -> None: ...
200
def discard(self) -> None: ...
201
```
202
203
[Pipelines and Transactions](./pipelines-transactions.md)
204
205
### Pub/Sub Messaging
206
207
Publish/subscribe messaging system for real-time communication between Redis clients.
208
209
```python { .api }
210
class PubSub:
211
def subscribe(self, *args, **kwargs) -> None: ...
212
def unsubscribe(self, *args) -> None: ...
213
def psubscribe(self, *args, **kwargs) -> None: ...
214
def listen(self) -> Iterator[Dict[str, Any]]: ...
215
def get_message(self, ignore_subscribe_messages: bool = False) -> Optional[Dict[str, Any]]: ...
216
```
217
218
[Pub/Sub Messaging](./pubsub-messaging.md)
219
220
### Distributed Locking
221
222
Distributed lock implementation for coordinating access to shared resources across multiple Redis clients.
223
224
```python { .api }
225
class Lock:
226
def acquire(self, blocking: bool = True, timeout: Optional[float] = None) -> bool: ...
227
def release(self) -> None: ...
228
def extend(self, additional_time: float) -> bool: ...
229
```
230
231
[Distributed Locking](./distributed-locking.md)
232
233
### Error Handling
234
235
Comprehensive exception hierarchy for handling Redis-specific errors and connection issues.
236
237
```python { .api }
238
class RedisError(Exception): ...
239
class ConnectionError(RedisError): ...
240
class TimeoutError(RedisError): ...
241
class ResponseError(RedisError): ...
242
class AuthenticationError(ConnectionError): ...
243
class RedisClusterException(RedisError): ...
244
```
245
246
[Error Handling](./error-handling.md)
247
248
### Redis Modules
249
250
Extended functionality through Redis modules providing advanced data structures and capabilities.
251
252
#### RedisJSON
253
254
Native JSON data type support with path-based operations for efficient document storage and manipulation. Access via `redis_client.json()`.
255
256
```python { .api }
257
# JSON client obtained via r.json()
258
class JSON:
259
def set(self, name: str, path: str, obj: Any, **kwargs) -> Optional[str]: ...
260
def get(self, name: str, *args: str, **kwargs) -> Optional[List[Any]]: ...
261
def delete(self, name: str, path: str = "$") -> Optional[int]: ...
262
def arrappend(self, name: str, path: str, *args: Any) -> List[Optional[int]]: ...
263
def numincrby(self, name: str, path: str, number: int) -> str: ...
264
```
265
266
[RedisJSON](./modules/redis-json.md)
267
268
#### RediSearch
269
270
Full-text search, secondary indexing, and query capabilities with aggregations and auto-complete.
271
272
```python { .api }
273
def ft_create(self, index_name: str, schema: Dict[str, Any], **kwargs) -> str: ...
274
def ft_search(self, index_name: str, query: str, **kwargs) -> Dict[str, Any]: ...
275
def ft_aggregate(self, index_name: str, query: str, *args: Any) -> List[Any]: ...
276
def ft_sugadd(self, key: str, string: str, score: float, **kwargs) -> int: ...
277
def ft_sugget(self, key: str, prefix: str, **kwargs) -> List[Any]: ...
278
```
279
280
[RediSearch](./modules/redis-search.md)
281
282
#### RedisTimeSeries
283
284
Time series data structure for efficient storage and analysis of time-stamped data with downsampling and aggregations.
285
286
```python { .api }
287
def ts_create(self, key: str, **kwargs) -> str: ...
288
def ts_add(self, key: str, timestamp: Union[int, str], value: float, **kwargs) -> int: ...
289
def ts_get(self, key: str) -> Optional[Tuple[int, float]]: ...
290
def ts_range(self, key: str, from_timestamp: Union[int, str], to_timestamp: Union[int, str], **kwargs) -> List[Tuple[int, float]]: ...
291
def ts_mrange(self, from_timestamp: Union[int, str], to_timestamp: Union[int, str], filters: List[str], **kwargs) -> List[Dict[str, Any]]: ...
292
```
293
294
[RedisTimeSeries](./modules/redis-timeseries.md)
295
296
#### RedisBloom
297
298
Probabilistic data structures including Bloom filters, Cuckoo filters, Count-Min Sketch, and Top-K for memory-efficient approximate queries.
299
300
```python { .api }
301
def bf_reserve(self, key: str, error_rate: float, capacity: int) -> str: ...
302
def bf_add(self, key: str, item: str) -> bool: ...
303
def bf_exists(self, key: str, item: str) -> bool: ...
304
def cf_reserve(self, key: str, capacity: int, **kwargs) -> str: ...
305
def cms_initbyprob(self, key: str, error: float, probability: float) -> str: ...
306
def topk_reserve(self, key: str, k: int, width: int, depth: int, decay: float) -> str: ...
307
```
308
309
[RedisBloom](./modules/redis-bloom.md)
310
311
## Types
312
313
```python { .api }
314
from typing import Any, Dict, List, Optional, Union, Tuple, Iterator, Type
315
316
# Key types
317
KeyT = Union[str, bytes]
318
FieldT = Union[str, bytes]
319
EncodableT = Union[bytes, float, int, str]
320
ExpiryT = Union[int, datetime.timedelta]
321
322
# Connection types
323
ConnectionT = Union[Connection, SSLConnection, UnixDomainSocketConnection]
324
325
# Cluster types
326
class ClusterNode:
327
def __init__(self, host: str, port: int, server_type: Optional[str] = None): ...
328
host: str
329
port: int
330
331
# Credential types
332
class CredentialProvider:
333
def get_credentials(self) -> Tuple[str, str]: ...
334
```