Skip to content

Commit

Permalink
Making list length fetching support globs
Browse files Browse the repository at this point in the history
Making each configured instance have its own class to avoid global variables
  • Loading branch information
Ben Keith committed Nov 10, 2017
1 parent 3f4dd02 commit 6697cd9
Show file tree
Hide file tree
Showing 3 changed files with 260 additions and 225 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ You can capture any kind of Redis metrics like:
* Uptime
* Changes since last save
* Replication delay (per slave)
* The length of list values


Installation and Configuration
Expand Down
64 changes: 64 additions & 0 deletions redis_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
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('r')

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("%s\r\n" % message)

def read_response(self):
first_line = self.file.readline()
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)
# Get rid of \r\n at end
self.file.read(2)

return s


class RedisError(Exception):
pass
Loading

0 comments on commit 6697cd9

Please sign in to comment.