forked from powdahound/redis-collectd-plugin
-
Notifications
You must be signed in to change notification settings - Fork 8
/
redis_client.py
65 lines (48 loc) · 1.76 KB
/
redis_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import socket
class RedisClient:
def __init__(self, host, port, auth):
self.host = host
self.port = port
self.auth = auth
def connect(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((self.host, self.port))
self.file = self.socket.makefile("rb")
if self.auth is not None:
self.send("auth %s" % (self.auth))
self.read_response()
def __enter__(self):
self.connect()
return self
def __exit__(self, *args):
if self.socket:
self.socket.close()
def send(self, message):
return self.socket.sendall(message.encode("utf-8") + b"\r\n")
def read_response(self):
first_line = self.file.readline().decode("utf-8")
if first_line.startswith("-"):
raise RedisError(first_line)
if first_line.startswith("*"):
return self.read_array(first_line)
elif first_line.startswith("$"):
return self.read_bulk_string(first_line)
elif first_line.startswith(":"):
return first_line.lstrip(":").rstrip()
elif first_line.startswith("+"):
return first_line.lstrip("+").rstrip()
else:
raise ValueError("Unknown Redis response: %s" % first_line)
def read_array(self, first_line):
size = int(first_line.lstrip("*").rstrip())
return [self.read_response() for i in range(0, size)]
def read_bulk_string(self, first_line):
size = int(first_line.lstrip("$").rstrip())
if size == -1:
return None
s = self.file.read(size).decode("utf-8")
# Get rid of \r\n at end
self.file.read(2)
return s
class RedisError(Exception):
pass