0
# Core Client
1
2
The Redis class provides the main interface for interacting with Redis server instances. It supports all standard Redis data types and operations with comprehensive configuration options.
3
4
```python
5
import redis
6
import ssl
7
from typing import TYPE_CHECKING, Optional, Union, List, Dict, Set, Tuple, Callable, Mapping, Type
8
9
from redis import Redis, ConnectionPool
10
from redis.credentials import CredentialProvider
11
from redis.retry import Retry
12
from redis.backoff import ExponentialWithJitterBackoff
13
from redis.cache import CacheInterface, CacheConfig
14
from redis.event import EventDispatcher
15
16
# Type checking imports
17
if TYPE_CHECKING:
18
import OpenSSL
19
```
20
21
## Capabilities
22
23
### Client Initialization
24
25
Create Redis client instances with various connection options and configurations.
26
27
```python { .api }
28
class Redis:
29
def __init__(
30
self,
31
host: str = "localhost",
32
port: int = 6379,
33
db: int = 0,
34
password: Optional[str] = None,
35
socket_timeout: Optional[float] = None,
36
socket_connect_timeout: Optional[float] = None,
37
socket_keepalive: Optional[bool] = None,
38
socket_keepalive_options: Optional[Mapping[int, Union[int, bytes]]] = None,
39
connection_pool: Optional[ConnectionPool] = None,
40
unix_socket_path: Optional[str] = None,
41
encoding: str = "utf-8",
42
encoding_errors: str = "strict",
43
decode_responses: bool = False,
44
retry_on_timeout: bool = False,
45
retry: Retry = Retry(
46
backoff=ExponentialWithJitterBackoff(base=1, cap=10), retries=3
47
),
48
retry_on_error: Optional[List[Type[Exception]]] = None,
49
ssl: bool = False,
50
ssl_keyfile: Optional[str] = None,
51
ssl_certfile: Optional[str] = None,
52
ssl_cert_reqs: Union[str, "ssl.VerifyMode"] = "required",
53
ssl_ca_certs: Optional[str] = None,
54
ssl_ca_path: Optional[str] = None,
55
ssl_ca_data: Optional[str] = None,
56
ssl_check_hostname: bool = True,
57
ssl_password: Optional[str] = None,
58
ssl_validate_ocsp: bool = False,
59
ssl_validate_ocsp_stapled: bool = False,
60
ssl_ocsp_context: Optional["OpenSSL.SSL.Context"] = None,
61
ssl_ocsp_expected_cert: Optional[str] = None,
62
ssl_min_version: Optional["ssl.TLSVersion"] = None,
63
ssl_ciphers: Optional[str] = None,
64
max_connections: Optional[int] = None,
65
single_connection_client: bool = False,
66
health_check_interval: int = 0,
67
client_name: Optional[str] = None,
68
lib_name: Optional[str] = "redis-py",
69
lib_version: Optional[str] = None,
70
username: Optional[str] = None,
71
retry_on_timeout: bool = False,
72
retry_on_error: Optional[List[Type[Exception]]] = None,
73
redis_connect_func: Optional[Callable[[], None]] = None,
74
credential_provider: Optional[CredentialProvider] = None,
75
protocol: Optional[int] = 2,
76
cache: Optional[CacheInterface] = None,
77
cache_config: Optional[CacheConfig] = None,
78
event_dispatcher: Optional[EventDispatcher] = None
79
): ...
80
81
@classmethod
82
def from_url(
83
cls,
84
url: str,
85
**kwargs
86
) -> "Redis": ...
87
88
@classmethod
89
def from_pool(
90
cls,
91
connection_pool: ConnectionPool
92
) -> "Redis": ...
93
```
94
95
### String Operations
96
97
Redis string operations for storing and manipulating string values.
98
99
```python { .api }
100
def set(
101
self,
102
name: KeyT,
103
value: EncodableT,
104
ex: Optional[ExpiryT] = None,
105
px: Optional[int] = None,
106
nx: bool = False,
107
xx: bool = False,
108
keepttl: bool = False,
109
get: bool = False,
110
exat: Optional[int] = None,
111
pxat: Optional[int] = None
112
) -> Optional[bool]: ...
113
114
def get(self, name: KeyT) -> Optional[bytes]: ...
115
116
def mget(self, keys: List[KeyT], *args: KeyT) -> List[Optional[bytes]]: ...
117
118
def mset(self, mapping: Dict[KeyT, EncodableT]) -> bool: ...
119
120
def setex(self, name: KeyT, time: ExpiryT, value: EncodableT) -> bool: ...
121
122
def setnx(self, name: KeyT, value: EncodableT) -> bool: ...
123
124
def incr(self, name: KeyT, amount: int = 1) -> int: ...
125
126
def decr(self, name: KeyT, amount: int = 1) -> int: ...
127
128
def append(self, key: KeyT, value: EncodableT) -> int: ...
129
130
def substr(self, name: KeyT, start: int, end: int = -1) -> bytes: ...
131
132
def strlen(self, name: KeyT) -> int: ...
133
```
134
135
### Hash Operations
136
137
Redis hash operations for storing and manipulating hash (dictionary-like) values.
138
139
```python { .api }
140
def hset(
141
self,
142
name: KeyT,
143
key: Optional[FieldT] = None,
144
value: Optional[EncodableT] = None,
145
mapping: Optional[Dict[FieldT, EncodableT]] = None
146
) -> int: ...
147
148
def hget(self, name: KeyT, key: FieldT) -> Optional[bytes]: ...
149
150
def hgetall(self, name: KeyT) -> Dict[bytes, bytes]: ...
151
152
def hmget(self, name: KeyT, keys: List[FieldT], *args: FieldT) -> List[Optional[bytes]]: ...
153
154
def hmset(self, name: KeyT, mapping: Dict[FieldT, EncodableT]) -> bool: ...
155
156
def hkeys(self, name: KeyT) -> List[bytes]: ...
157
158
def hvals(self, name: KeyT) -> List[bytes]: ...
159
160
def hlen(self, name: KeyT) -> int: ...
161
162
def hexists(self, name: KeyT, key: FieldT) -> bool: ...
163
164
def hdel(self, name: KeyT, *keys: FieldT) -> int: ...
165
166
def hincrby(self, name: KeyT, key: FieldT, amount: int = 1) -> int: ...
167
168
def hincrbyfloat(self, name: KeyT, key: FieldT, amount: float = 1.0) -> float: ...
169
```
170
171
### List Operations
172
173
Redis list operations for storing and manipulating ordered collections.
174
175
```python { .api }
176
def lpush(self, name: KeyT, *values: EncodableT) -> int: ...
177
178
def rpush(self, name: KeyT, *values: EncodableT) -> int: ...
179
180
def lpop(self, name: KeyT, count: Optional[int] = None) -> Union[Optional[bytes], List[bytes]]: ...
181
182
def rpop(self, name: KeyT, count: Optional[int] = None) -> Union[Optional[bytes], List[bytes]]: ...
183
184
def llen(self, name: KeyT) -> int: ...
185
186
def lrange(self, name: KeyT, start: int, end: int) -> List[bytes]: ...
187
188
def ltrim(self, name: KeyT, start: int, end: int) -> bool: ...
189
190
def lindex(self, name: KeyT, index: int) -> Optional[bytes]: ...
191
192
def lset(self, name: KeyT, index: int, value: EncodableT) -> bool: ...
193
194
def lrem(self, name: KeyT, count: int, value: EncodableT) -> int: ...
195
196
def linsert(
197
self,
198
name: KeyT,
199
where: str,
200
refvalue: EncodableT,
201
value: EncodableT
202
) -> int: ...
203
204
def blpop(self, keys: List[KeyT], timeout: int = 0) -> Optional[Tuple[bytes, bytes]]: ...
205
206
def brpop(self, keys: List[KeyT], timeout: int = 0) -> Optional[Tuple[bytes, bytes]]: ...
207
```
208
209
### Set Operations
210
211
Redis set operations for storing and manipulating unordered collections of unique elements.
212
213
```python { .api }
214
def sadd(self, name: KeyT, *values: EncodableT) -> int: ...
215
216
def srem(self, name: KeyT, *values: EncodableT) -> int: ...
217
218
def smembers(self, name: KeyT) -> Set[bytes]: ...
219
220
def scard(self, name: KeyT) -> int: ...
221
222
def sismember(self, name: KeyT, value: EncodableT) -> bool: ...
223
224
def spop(self, name: KeyT, count: Optional[int] = None) -> Union[Optional[bytes], List[bytes]]: ...
225
226
def srandmember(self, name: KeyT, number: Optional[int] = None) -> Union[Optional[bytes], List[bytes]]: ...
227
228
def sunion(self, keys: List[KeyT], *args: KeyT) -> Set[bytes]: ...
229
230
def sinter(self, keys: List[KeyT], *args: KeyT) -> Set[bytes]: ...
231
232
def sdiff(self, keys: List[KeyT], *args: KeyT) -> Set[bytes]: ...
233
234
def sunionstore(self, dest: KeyT, keys: List[KeyT], *args: KeyT) -> int: ...
235
236
def sinterstore(self, dest: KeyT, keys: List[KeyT], *args: KeyT) -> int: ...
237
238
def sdiffstore(self, dest: KeyT, keys: List[KeyT], *args: KeyT) -> int: ...
239
```
240
241
### Sorted Set Operations
242
243
Redis sorted set operations for storing ordered collections with scores.
244
245
```python { .api }
246
def zadd(
247
self,
248
name: KeyT,
249
mapping: Dict[EncodableT, float],
250
nx: bool = False,
251
xx: bool = False,
252
ch: bool = False,
253
incr: bool = False,
254
gt: bool = False,
255
lt: bool = False
256
) -> Union[int, float]: ...
257
258
def zrem(self, name: KeyT, *values: EncodableT) -> int: ...
259
260
def zrange(
261
self,
262
name: KeyT,
263
start: int,
264
end: int,
265
desc: bool = False,
266
withscores: bool = False,
267
score_cast_func: Callable[[bytes], float] = float
268
) -> Union[List[bytes], List[Tuple[bytes, float]]]: ...
269
270
def zrevrange(
271
self,
272
name: KeyT,
273
start: int,
274
end: int,
275
withscores: bool = False,
276
score_cast_func: Callable[[bytes], float] = float
277
) -> Union[List[bytes], List[Tuple[bytes, float]]]: ...
278
279
def zcard(self, name: KeyT) -> int: ...
280
281
def zcount(self, name: KeyT, min: Union[float, str], max: Union[float, str]) -> int: ...
282
283
def zscore(self, name: KeyT, value: EncodableT) -> Optional[float]: ...
284
285
def zrank(self, name: KeyT, value: EncodableT) -> Optional[int]: ...
286
287
def zrevrank(self, name: KeyT, value: EncodableT) -> Optional[int]: ...
288
289
def zincrby(self, name: KeyT, amount: float, value: EncodableT) -> float: ...
290
```
291
292
### Key Management
293
294
Redis key management operations for working with keys across all data types.
295
296
```python { .api }
297
def exists(self, *names: KeyT) -> int: ...
298
299
def delete(self, *names: KeyT) -> int: ...
300
301
def expire(self, name: KeyT, time: ExpiryT) -> bool: ...
302
303
def expireat(self, name: KeyT, when: int) -> bool: ...
304
305
def ttl(self, name: KeyT) -> int: ...
306
307
def persist(self, name: KeyT) -> bool: ...
308
309
def move(self, name: KeyT, db: int) -> bool: ...
310
311
def rename(self, src: KeyT, dst: KeyT) -> bool: ...
312
313
def renamenx(self, src: KeyT, dst: KeyT) -> bool: ...
314
315
def randomkey(self) -> Optional[bytes]: ...
316
317
def type(self, name: KeyT) -> bytes: ...
318
319
def keys(self, pattern: str = "*") -> List[bytes]: ...
320
321
def scan(
322
self,
323
cursor: int = 0,
324
match: Optional[str] = None,
325
count: Optional[int] = None,
326
type: Optional[str] = None
327
) -> Tuple[int, List[bytes]]: ...
328
329
def sort(
330
self,
331
name: KeyT,
332
start: Optional[int] = None,
333
num: Optional[int] = None,
334
by: Optional[str] = None,
335
get: Optional[List[str]] = None,
336
desc: bool = False,
337
alpha: bool = False,
338
store: Optional[KeyT] = None
339
) -> List[bytes]: ...
340
```
341
342
### Server Operations
343
344
Redis server administration and information operations.
345
346
```python { .api }
347
def ping(self, **kwargs) -> Union[bytes, bool]: ...
348
349
def echo(self, value: EncodableT) -> bytes: ...
350
351
def info(self, section: Optional[str] = None) -> Dict[str, Any]: ...
352
353
def dbsize(self) -> int: ...
354
355
def flushdb(self, asynchronous: bool = False) -> bool: ...
356
357
def flushall(self, asynchronous: bool = False) -> bool: ...
358
359
def save(self) -> bool: ...
360
361
def bgsave(self, schedule: bool = True) -> bool: ...
362
363
def bgrewriteaof(self) -> bool: ...
364
365
def lastsave(self) -> int: ...
366
367
def shutdown(self, save: bool = False, nosave: bool = False) -> None: ...
368
369
def config_get(self, pattern: str = "*") -> Dict[str, str]: ...
370
371
def config_set(self, name: str, value: EncodableT) -> bool: ...
372
373
def config_resetstat(self) -> bool: ...
374
375
def config_rewrite(self) -> bool: ...
376
377
def client_list(self, type: Optional[str] = None) -> List[Dict[str, str]]: ...
378
379
def client_info(self) -> Dict[str, str]: ...
380
381
def client_setname(self, name: str) -> bool: ...
382
383
def client_getname(self) -> Optional[bytes]: ...
384
385
def client_id(self) -> int: ...
386
387
def client_kill(self, address: str) -> bool: ...
388
389
def close(self) -> None: ...
390
```
391
392
## Usage Examples
393
394
### Basic Key-Value Operations
395
396
```python
397
import redis
398
399
# Connect to Redis
400
r = redis.Redis(host='localhost', port=6379, db=0)
401
402
# String operations
403
r.set('user:1001:name', 'John Doe')
404
name = r.get('user:1001:name') # b'John Doe'
405
406
# Set with expiration
407
r.setex('session:abc123', 3600, 'session_data') # Expires in 1 hour
408
409
# Increment counter
410
r.incr('page_views') # Returns new count
411
```
412
413
### Working with Complex Data Types
414
415
```python
416
# Hash operations - user profile
417
r.hset('user:1001', mapping={
418
'name': 'John Doe',
419
'email': 'john@example.com',
420
'age': '30'
421
})
422
profile = r.hgetall('user:1001')
423
424
# List operations - activity log
425
r.lpush('user:1001:activity', 'logged_in', 'viewed_dashboard')
426
recent_activity = r.lrange('user:1001:activity', 0, 4)
427
428
# Set operations - user tags
429
r.sadd('user:1001:tags', 'premium', 'active', 'verified')
430
tags = r.smembers('user:1001:tags')
431
432
# Sorted set operations - leaderboard
433
r.zadd('leaderboard', {'player1': 1000, 'player2': 1500, 'player3': 800})
434
top_players = r.zrevrange('leaderboard', 0, 2, withscores=True)
435
```
436
437
### Connection from URL
438
439
```python
440
import redis
441
442
# Connect using URL
443
r = redis.from_url('redis://localhost:6379/0')
444
445
# Connect with authentication
446
r = redis.from_url('redis://:password@localhost:6379/0')
447
448
# Connect with SSL
449
r = redis.from_url('rediss://localhost:6380/0')
450
```