0
# Redis Client Classes
1
2
Enhanced Redis client classes that automatically manage embedded Redis server instances. These classes provide all the functionality of redis-py Redis classes with additional embedded server management capabilities.
3
4
## Capabilities
5
6
### Redis Class
7
8
Enhanced version of the redis.Redis() class that uses an embedded redis-server by default.
9
10
```python { .api }
11
class Redis(RedisMixin, redis.Redis):
12
"""
13
Enhanced Redis client with embedded server management.
14
15
Parameters:
16
dbfilename (str, optional): Path to the redis rdb file to back the redis instance
17
serverconfig (dict, optional): Dictionary containing redis server settings
18
host (str, optional): Hostname or IP address of redis server to connect to
19
port (int, optional): Port number of redis server to connect to
20
**kwargs: All other keyword arguments supported by redis.Redis()
21
22
Attributes:
23
db (str): The fully qualified filename associated with the redis dbfilename
24
pid (int): Pid of the running embedded redis server (read only)
25
redis_log (str): The contents of the redis-server log file
26
start_timeout (float): Number of seconds to wait for server start
27
"""
28
29
def redis_log_tail(self, lines=1, width=80):
30
"""
31
The redis log output.
32
33
Parameters:
34
lines (int, optional): Number of lines from the end of logfile to return
35
width (int, optional): Expected average width of a log file line
36
37
Returns:
38
list: List of strings containing the lines from the logfile
39
"""
40
```
41
42
**Usage Examples:**
43
44
```python
45
from redislite import Redis
46
47
# Create with default temporary database
48
redis_conn = Redis()
49
50
# Create with specific database file
51
redis_conn = Redis('/tmp/my_redis.db')
52
53
# Create with custom server configuration
54
redis_conn = Redis(
55
'/tmp/redis.db',
56
serverconfig={
57
'port': '8002',
58
'databases': '32'
59
}
60
)
61
62
# Use like any Redis connection
63
redis_conn.set('key', 'value')
64
value = redis_conn.get('key')
65
66
# Access server information
67
print(f"Server PID: {redis_conn.pid}")
68
print(f"Database file: {redis_conn.db}")
69
70
# View server logs
71
recent_logs = redis_conn.redis_log_tail(lines=10)
72
all_logs = redis_conn.redis_log
73
```
74
75
### StrictRedis Class
76
77
Enhanced version of the redis.StrictRedis() class that uses an embedded redis-server by default.
78
79
```python { .api }
80
class StrictRedis(RedisMixin, redis.StrictRedis):
81
"""
82
Enhanced StrictRedis client with embedded server management.
83
84
Parameters:
85
dbfilename (str, optional): Path to the redis rdb file to back the redis instance
86
serverconfig (dict, optional): Dictionary containing redis server settings
87
host (str, optional): Hostname or IP address of redis server to connect to
88
port (int, optional): Port number of redis server to connect to
89
**kwargs: All other keyword arguments supported by redis.StrictRedis()
90
91
Attributes:
92
db (str): The fully qualified filename associated with the redis dbfilename
93
pid (int): Pid of the running embedded redis server (read only)
94
redis_log (str): The contents of the redis-server log file
95
start_timeout (float): Number of seconds to wait for server start
96
"""
97
```
98
99
**Usage Examples:**
100
101
```python
102
from redislite import StrictRedis
103
104
# Create StrictRedis instance
105
redis_conn = StrictRedis('/tmp/strict_redis.db')
106
107
# Use like any StrictRedis connection
108
redis_conn.set('counter', 0)
109
redis_conn.incr('counter')
110
value = redis_conn.get('counter') # Returns b'1'
111
```
112
113
### RedisMixin
114
115
The core mixin class that provides embedded server management functionality to both Redis and StrictRedis classes.
116
117
```python { .api }
118
class RedisMixin:
119
"""
120
Extended version of the redis.Redis class with code to start/stop the
121
embedded redis server based on the passed arguments.
122
123
Attributes:
124
redis_dir (str): Directory for redis instance files
125
pidfile (str): Path to redis pid file
126
socket_file (str): Path to redis unix socket file
127
start_timeout (int): Timeout for server start (default: 10)
128
running (bool): Whether redis server is running
129
dbfilename (str): Database filename (default: 'redis.db')
130
dbdir (str): Database directory
131
"""
132
133
@property
134
def redis_log(self):
135
"""
136
Redis server log content as a string.
137
138
Returns:
139
str: Log contents
140
"""
141
142
@property
143
def db(self):
144
"""
145
Return the connection string to allow connecting to the same redis server.
146
147
Returns:
148
str: Connection path
149
"""
150
151
@property
152
def pid(self):
153
"""
154
Get the current redis-server process id.
155
156
Returns:
157
int: The process id of the redis-server process or 0 if not running
158
"""
159
160
def redis_log_tail(self, lines=1, width=80):
161
"""
162
The redis log output.
163
164
Parameters:
165
lines (int, optional): Number of lines from end of logfile (0 = all lines)
166
width (int, optional): Expected average width of log file line
167
168
Returns:
169
list: List of strings containing the lines from the logfile
170
"""
171
```
172
173
### Multiple Server Instances
174
175
Create multiple independent Redis servers or share servers via database files.
176
177
**Usage Examples:**
178
179
```python
180
import redislite
181
182
# Create multiple independent servers
183
servers = {}
184
for i in range(3):
185
servers[i] = redislite.Redis() # Each gets its own server
186
servers[i].set('server_id', i)
187
188
# Create multiple clients sharing the same server
189
shared_db = '/tmp/shared.db'
190
client1 = redislite.Redis(shared_db)
191
client2 = redislite.Redis(shared_db) # Shares server with client1
192
193
client1.set('shared_key', 'value')
194
print(client2.get('shared_key')) # b'value'
195
```
196
197
### Master-Slave Configuration
198
199
Set up Redis replication using server configuration.
200
201
**Usage Examples:**
202
203
```python
204
import redislite
205
206
# Create master server on port 8002
207
master = redislite.Redis(serverconfig={'port': '8002'})
208
209
# Create slave server that replicates from master
210
slave = redislite.Redis(serverconfig={'slaveof': '127.0.0.1 8002'})
211
212
# Set data on master
213
master.set('replicated_key', 'replicated_value')
214
215
# Data is available on slave
216
print(slave.get('replicated_key')) # b'replicated_value'
217
```
218
219
## Exception Handling
220
221
```python { .api }
222
class RedisLiteException(Exception):
223
"""Redislite Client Error exception class"""
224
225
class RedisLiteServerStartError(Exception):
226
"""Redislite redis-server start error"""
227
```
228
229
**Usage Examples:**
230
231
```python
232
from redislite import Redis, RedisLiteServerStartError
233
234
try:
235
redis_conn = Redis()
236
redis_conn.ping()
237
except RedisLiteServerStartError as e:
238
print(f"Failed to start Redis server: {e}")
239
```