Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 72 additions & 10 deletions ssdb/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from __future__ import with_statement
from itertools import chain, starmap, izip_longest
import datetime
import re
import sys
import warnings
import time as mod_time
Expand Down Expand Up @@ -79,6 +80,48 @@ def list_to_int_ordereddict(lst):
dst[k] = int(v)
return dst

def parse_info(lst):
res = dict(izip_longest(*[iter(lst[1:])] * 2, fillvalue=None))
if 'binlogs' in res:
binlogs = re.split(r"[\W\n:]+", res['binlogs'].strip())
res['binlogs'] = dict(zip(binlogs[::2], map(int, binlogs[1::2])))
if 'data_key_range' in res:
data_key_range = re.split(r" *[\n:] +", res['data_key_range'].strip())
res['data_key_range'] = dict(zip(data_key_range[::2], data_key_range[1::2]))
if 'serv_key_range' in res:
serv_key_range = re.split(r" *[\n:] +", res['serv_key_range'].strip())
res['serv_key_range'] = dict(zip(serv_key_range[::2], serv_key_range[1::2]))
if 'leveldb.stats' in res:
leveldb_stats = res.pop('leveldb.stats').strip().split('\n')
stats_list = []
headers = []
for line in leveldb_stats:
if line.find('Level') >= 0:
headers = line.strip().split()
elif line.find('Compactions') >= 0:
continue
elif line.find('------') == -1:
stats = map(int, line.strip().split())
stats_dict = dict()
for i in range(len(headers)):
stats_dict[headers[i]] = stats[i]
if int(stats[0]) == len(stats_list):
stats_list.append(stats_dict)
res['leveldb'] = {}
res['leveldb']['stats'] = stats_list
res['name'] = lst[0]
for key in res.keys():
if isinstance(res[key], str):
if key.find('cmd.') == 0:
key_stats = re.split(r"[\t:]+", res.pop(key).strip())
key = key.split('.')[1]
if 'cmd' not in res:
res['cmd'] = {}
res['cmd'][key] = dict(zip(key_stats[::2], map(int, key_stats[1::2])))
elif res[key].isdigit():
res[key] = int(res[key])
return res

def dict_to_list(dct):
lst = []
for key, value in dct.iteritems():
Expand Down Expand Up @@ -170,24 +213,29 @@ class StrictSSDB(object):
string_keys_to_dict(
'multi_zget',
list_to_int_dict
),
),
string_keys_to_dict(
'keys hkeys hlist hrlist zkeys zlist zrlist '
'qlist qrlist qrange qslice qpop_back qpop_front',
lambda r: r
),
),
string_keys_to_dict(
'info',
parse_info
),
{
'qset': lambda r: True,
}
)

def __init__(self, host='localhost', port=8888, socket_timeout=None,
def __init__(self, host='localhost', port=8888, password=None, socket_timeout=None,
connection_pool=None, charset='utf-8', errors='strict',
decode_responses=False):
if not connection_pool:
kwargs = {
'host': host,
'port': port,
'password': password,
'socket_timeout': socket_timeout,
'encoding': charset,
'encoding_errors': errors,
Expand Down Expand Up @@ -373,8 +421,9 @@ def expire(self, name, ttl):
>>> ssdb.expire('not_exist')
False
"""
if isinstance(time, datetime.timedelta):
time = time.seconds + time.days * 24 * 3600
if isinstance(ttl, datetime.timedelta):
ttl = ttl.seconds + ttl.days * 24 * 3600
ttl = get_positive_integer('ttl', ttl)
return self.execute_command('expire', name, ttl)

def ttl(self, name):
Expand All @@ -395,9 +444,7 @@ def ttl(self, name):
>>> ssdb.ttl('not_exist')
-1
"""
if isinstance(time, datetime.timedelta):
time = time.seconds + time.days * 24 * 3600
return self.execute_command('expire', name, ttl)
return self.execute_command('ttl', name)

def exists(self, name):
"""
Expand Down Expand Up @@ -2129,8 +2176,23 @@ def queue_exists(self, name):
return hsize(name) > 0
except:
return False



def info(self, opt=None):
"""
Returns a dictionary containing information about the SSDB server

The ``section`` option can be used to select a specific section
of information

:param string opt: `cmd` or `leveldb`
:return: Server Info Dict
:rtype: dict
"""
if opt is None:
return self.execute_command('info')
else:
return self.execute_command('info', opt)

class SSDB(StrictSSDB):
"""
Provides backwards compatibility with older versions of ssdb-py(1.6.6) that changed
Expand Down
7 changes: 6 additions & 1 deletion ssdb/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ class Connection(object):

description_format = "Connection<host=%(host)s,port=%(port)s>"

def __init__(self, host="127.0.0.1",port=8888,socket_timeout=None,
def __init__(self, host="127.0.0.1",port=8888, password=None, socket_timeout=None,
socket_connect_timeout=None,socket_keepalive=False,
socket_keepalive_options=None,retry_on_timeout=False,
encoding='utf-8', encoding_errors='strict',
Expand All @@ -236,6 +236,7 @@ def __init__(self, host="127.0.0.1",port=8888,socket_timeout=None,
self.pid = os.getpid()
self.host = host
self.port = port
self.password = password
self._sock = None
self.socket_timeout = socket_timeout
self.socket_connect_timeout = socket_connect_timeout or socket_timeout
Expand Down Expand Up @@ -355,6 +356,10 @@ def on_connect(self):
Initialize the connection
"""
self._parser.on_connect(self)
if self.password:
self.send_command("auth", self.password)
if nativestr(self.read_response()[0]) != 'ok':
raise AuthenticationError("Invalid Password")

def disconnect(self):
"""
Expand Down