This repository was archived by the owner on Apr 3, 2019. It is now read-only.
forked from evilkost/brukva
-
Notifications
You must be signed in to change notification settings - Fork 161
/
Copy pathclient.py
1527 lines (1220 loc) · 54.1 KB
/
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import sys
from functools import partial
import collections
from collections import namedtuple, deque
import logging
import weakref
import datetime
import time as mod_time
from tornado.ioloop import IOLoop
from tornado import gen
from tornado import stack_context
from tornado.escape import to_unicode, to_basestring
from .exceptions import RequestError, ConnectionError, ResponseError
from .connection import Connection
log = logging.getLogger('tornadoredis.client')
Message = namedtuple('Message', ('kind', 'channel', 'body', 'pattern'))
PY3 = sys.version > '3'
if not PY3:
from itertools import imap
basestring = basestring
unicode = unicode
bytes = str
long = long
b = lambda x: x
else:
imap = map
basestring = str
unicode = str
bytes = bytes
long = int
b = lambda x: x.encode('latin-1') if not isinstance(x, bytes) else x
SYM_STAR = b('*')
SYM_DOLLAR = b('$')
SYM_CRLF = b('\r\n')
SYM_EMPTY = b('')
class CmdLine(object):
def __init__(self, cmd, *args, **kwargs):
self.cmd = cmd
self.args = args
self.kwargs = kwargs
def __repr__(self):
return self.cmd + '(' + str(self.args) + ',' + str(self.kwargs) + ')'
def string_keys_to_dict(key_string, callback):
return dict([(key, callback) for key in key_string.split()])
def dict_merge(*dicts):
merged = {}
for d in dicts:
merged.update(d)
return merged
def reply_to_bool(r, *args, **kwargs):
return bool(r)
def make_reply_assert_msg(msg):
def reply_assert_msg(r, *args, **kwargs):
return r == msg
return reply_assert_msg
def reply_set(r, *args, **kwargs):
return set(r)
def reply_dict_from_pairs(r, *args, **kwargs):
return dict(zip(r[::2], r[1::2]))
def reply_str(r, *args, **kwargs):
return r or ''
def reply_int(r, *args, **kwargs):
return int(r) if r is not None else None
def reply_number(r, *args, **kwargs):
if r is not None:
num = float(r)
if not num.is_integer():
return num
else:
return int(num)
return None
def reply_datetime(r, *args, **kwargs):
return datetime.datetime.fromtimestamp(int(r))
def reply_pubsub_message(r, *args, **kwargs):
"""
Handles a Pub/Sub message and packs its data into a Message object.
"""
if len(r) == 3:
(kind, channel, body) = r
pattern = channel
elif len(r) == 4:
(kind, pattern, channel, body) = r
elif len(r) == 2:
(kind, channel) = r
body = pattern = None
else:
raise ValueError('Invalid number of arguments')
return Message(kind, channel, body, pattern)
def reply_zset(r, *args, **kwargs):
if r and 'WITHSCORES' in args:
return reply_zset_withscores(r, *args, **kwargs)
else:
return r
def reply_zset_withscores(r, *args, **kwargs):
return list(zip(r[::2], list(map(reply_number, r[1::2]))))
def reply_hmget(r, key, *fields, **kwargs):
return dict(list(zip(fields, r)))
def reply_info(response, *args):
info = {}
def get_value(value):
# Does this string contain subvalues?
if (',' not in value) or ('=' not in value):
return value
sub_dict = {}
for item in value.split(','):
k, v = item.split('=')
try:
sub_dict[k] = int(v)
except ValueError:
sub_dict[k] = v
return sub_dict
for line in response.splitlines():
line = line.strip().decode()
if line and not line.startswith('#'):
key, value = line.split(':')
try:
info[key] = int(value)
except ValueError:
info[key] = get_value(value)
return info
def reply_ttl(r, *args, **kwargs):
return r != -1 and r or None
def reply_map(*funcs):
def reply_fn(r, *args, **kwargs):
if len(funcs) != len(r):
raise ValueError('more results than functions to map')
return [f(part) for f, part in zip(funcs, r)]
return reply_fn
def to_list(source):
if isinstance(source, (bytes, str)):
return [source]
else:
return list(source)
PUB_SUB_COMMANDS = (
'SUBSCRIBE',
'PSUBSCRIBE',
'UNSUBSCRIBE',
'PUNSUBSCRIBE',
# Not a command at all
'LISTEN',
)
REPLY_MAP = dict_merge(
string_keys_to_dict('AUTH BGREWRITEAOF BGSAVE DEL EXISTS '
'EXPIRE HDEL HEXISTS '
'HMSET MOVE PERSIST RENAMENX SISMEMBER SMOVE '
'SETEX SAVE SETNX MSET',
reply_to_bool),
string_keys_to_dict('BITCOUNT DECRBY GETBIT HLEN INCRBY LINSERT '
'LPUSHX RPUSHX SADD SCARD SDIFFSTORE SETBIT SETRANGE '
'SINTERSTORE STRLEN SUNIONSTORE SETRANGE',
reply_int),
string_keys_to_dict('FLUSHALL FLUSHDB SELECT SET SETEX '
'SHUTDOWN RENAME RENAMENX WATCH UNWATCH',
make_reply_assert_msg('OK')),
string_keys_to_dict('SMEMBERS SINTER SUNION SDIFF',
reply_set),
string_keys_to_dict('HGETALL BRPOP BLPOP',
reply_dict_from_pairs),
string_keys_to_dict('HGET',
reply_str),
string_keys_to_dict('SUBSCRIBE UNSUBSCRIBE LISTEN '
'PSUBSCRIBE UNSUBSCRIBE',
reply_pubsub_message),
string_keys_to_dict('ZRANK ZREVRANK',
reply_int),
string_keys_to_dict('ZCOUNT ZCARD',
reply_int),
string_keys_to_dict('ZRANGE ZRANGEBYSCORE ZREVRANGE '
'ZREVRANGEBYSCORE',
reply_zset),
string_keys_to_dict('ZSCORE ZINCRBY',
reply_number),
string_keys_to_dict('SCAN HSCAN SSCAN',
reply_map(reply_int, reply_set)),
{'HMGET': reply_hmget,
'PING': make_reply_assert_msg('PONG'),
'LASTSAVE': reply_datetime,
'TTL': reply_ttl,
'INFO': reply_info,
'MULTI_PART': make_reply_assert_msg('QUEUED'),
'TIME': lambda x: (int(x[0]), int(x[1])),
'ZSCAN': reply_map(reply_int, reply_zset_withscores)}
)
class Client(object):
# __slots__ = ('_io_loop', '_connection_pool', 'connection', 'subscribed',
# 'password', 'selected_db', '_pipeline', '_weak')
def __init__(self, host='localhost', port=6379, unix_socket_path=None,
password=None, selected_db=None, io_loop=None,
connection_pool=None, encoding='utf-8', encoding_errors='strict'):
self._io_loop = io_loop or IOLoop.current()
self._connection_pool = connection_pool
self._weak = weakref.proxy(self)
if connection_pool:
connection = (connection_pool
.get_connection(event_handler_ref=self._weak))
else:
connection = Connection(host=host, port=port,
unix_socket_path=unix_socket_path,
event_handler_proxy=self._weak,
io_loop=self._io_loop)
self.connection = connection
self.subscribed = set()
self.subscribe_callbacks = deque()
self.unsubscribe_callbacks = []
self.password = password
self.selected_db = selected_db or 0
self._pipeline = None
self.encoding = encoding
self.encoding_errors = encoding_errors
def __del__(self):
try:
connection = self.connection
pool = self._connection_pool
except AttributeError:
connection = None
pool = None
if connection:
if pool:
pool.release(connection)
connection.wait_until_ready()
else:
connection.disconnect()
def __repr__(self):
return 'tornadoredis.Client (db=%s)' % (self.selected_db)
def __enter__(self):
return self
def __exit__(self, *args, **kwargs):
pass
def __getattribute__(self, item):
"""
Bind methods to the weak proxy to avoid memory leaks
when bound method is passed as argument to the gen.Task
constructor.
"""
a = super(Client, self).__getattribute__(item)
try:
if isinstance(a, collections.Callable) and a.__self__:
try:
a = self.__class__.__dict__[item]
except KeyError:
a = Client.__dict__[item]
a = partial(a, self._weak)
except AttributeError:
pass
return a
def pipeline(self, transactional=False):
"""
Creates the 'Pipeline' to send multiple redis commands
in a single request.
Usage:
pipe = self.client.pipeline()
pipe.hset('foo', 'bar', 1)
pipe.expire('foo', 60)
yield gen.Task(pipe.execute)
or:
with self.client.pipeline() as pipe:
pipe.hset('foo', 'bar', 1)
pipe.expire('foo', 60)
yield gen.Task(pipe.execute)
"""
if not self._pipeline:
self._pipeline = Pipeline(
transactional=transactional,
selected_db=self.selected_db,
password=self.password,
io_loop=self._io_loop,
)
self._pipeline.connection = self.connection
return self._pipeline
def on_disconnect(self):
if self.subscribed:
self.subscribed = set()
raise ConnectionError("Socket closed on remote end")
#### connection
def connect(self):
if not self.connection.connected():
pool = self._connection_pool
if pool:
old_conn = self.connection
self.connection = pool.get_connection(event_handler_ref=self)
self.connection.ready_callbacks = old_conn.ready_callbacks
else:
self.connection.connect()
@gen.engine
def disconnect(self, callback=None):
"""
Disconnects from the Redis server.
"""
connection = self.connection
if connection:
pool = self._connection_pool
if pool:
pool.release(connection)
yield gen.Task(connection.wait_until_ready)
proxy = pool.make_proxy(client_proxy=self._weak,
connected=False)
self.connection = proxy
else:
self.connection.disconnect()
if callback:
callback(False)
def encode(self, value):
"Return a bytestring representation of the value"
if isinstance(value, bytes):
return value
elif isinstance(value, (int, long)):
value = b(str(value))
elif isinstance(value, float):
value = b(repr(value))
elif not isinstance(value, basestring):
value = str(value)
if isinstance(value, unicode):
value = value.encode(self.encoding, self.encoding_errors)
return value
def format_command(self, *tokens, **kwargs):
cmds = []
buff = SYM_EMPTY.join((SYM_STAR, b(str(len(tokens))), SYM_CRLF))
for arg in imap(self.encode, tokens):
buff = SYM_EMPTY.join(
(buff, SYM_DOLLAR, b(str(len(arg))), SYM_CRLF, arg, SYM_CRLF))
return buff
def format_reply(self, cmd_line, data):
if cmd_line.cmd not in REPLY_MAP:
return data
try:
res = REPLY_MAP[cmd_line.cmd](data,
*cmd_line.args,
**cmd_line.kwargs)
except Exception as e:
raise ResponseError(
'failed to format reply to %s, raw data: %s; err message: %s'
% (cmd_line, data, e), cmd_line
)
return res
####
@gen.engine
def execute_command(self, cmd, *args, **kwargs):
result = None
execute_pending = cmd not in ('AUTH', 'SELECT')
callback = kwargs.get('callback', None)
if 'callback' in kwargs:
del kwargs['callback']
cmd_line = CmdLine(cmd, *args, **kwargs)
if callback and self.subscribed and cmd not in PUB_SUB_COMMANDS:
callback(RequestError(
'Executing non-Pub/Sub command while in subscribed state',
cmd_line))
return
n_tries = 2
while n_tries > 0:
n_tries -= 1
if not self.connection.connected():
self.connection.connect()
if not self.subscribed and not self.connection.ready():
yield gen.Task(self.connection.wait_until_ready)
if not self.subscribed and cmd not in ('AUTH', 'SELECT'):
if self.password and self.connection.info.get('pass', None) != self.password:
yield gen.Task(self.auth, self.password)
if self.selected_db and self.connection.info.get('db', 0) != self.selected_db:
yield gen.Task(self.select, self.selected_db)
command = self.format_command(cmd, *args, **kwargs)
try:
yield gen.Task(self.connection.write, command)
except Exception as e:
self.connection.disconnect()
if not n_tries:
raise e
else:
continue
listening = ((cmd in PUB_SUB_COMMANDS) or
(self.subscribed and cmd == 'PUBLISH'))
if listening:
result = True
execute_pending = False
break
else:
result = None
data = yield gen.Task(self.connection.readline)
if not data:
if not n_tries:
raise ConnectionError('no data received')
else:
resp = self.process_data(data, cmd_line)
if isinstance(resp, partial):
resp = yield gen.Task(resp)
result = self.format_reply(cmd_line, resp)
break
if execute_pending:
self.connection.execute_pending_command()
if callback:
callback(result)
@gen.engine
def _consume_bulk(self, tail, callback=None):
response = yield gen.Task(self.connection.read, int(tail) + 2)
if isinstance(response, Exception):
raise response
if not response:
raise ResponseError('EmptyResponse')
else:
response = response[:-2]
callback(response)
def process_data(self, data, cmd_line):
data = to_basestring(data)
data = data[:-2] # strip \r\n
if data == '$-1':
response = None
elif data == '*0' or data == '*-1':
response = []
else:
head, tail = data[0], data[1:]
if head == '*':
return partial(self.consume_multibulk, int(tail), cmd_line)
elif head == '$':
return partial(self._consume_bulk, tail)
elif head == '+':
response = tail
elif head == ':':
response = int(tail)
elif head == '-':
if tail.startswith('ERR'):
tail = tail[4:]
response = ResponseError(tail, cmd_line)
else:
raise ResponseError('Unknown response type %s' % head,
cmd_line)
return response
@gen.engine
def consume_multibulk(self, length, cmd_line, callback=None):
tokens = []
while len(tokens) < length:
data = yield gen.Task(self.connection.readline)
if not data:
raise ResponseError(
'Not enough data in response to %s, accumulated tokens: %s'
% (cmd_line, tokens),
cmd_line)
token = self.process_data(data, cmd_line)
if isinstance(token, partial):
token = yield gen.Task(token)
tokens.append(token)
callback(tokens)
### MAINTENANCE
def bgrewriteaof(self, callback=None):
self.execute_command('BGREWRITEAOF', callback=callback)
def dbsize(self, callback=None):
self.execute_command('DBSIZE', callback=callback)
def flushall(self, callback=None):
self.execute_command('FLUSHALL', callback=callback)
def flushdb(self, callback=None):
self.execute_command('FLUSHDB', callback=callback)
def ping(self, callback=None):
self.execute_command('PING', callback=callback)
def object(self, infotype, key, callback=None):
self.execute_command('OBJECT', infotype, key, callback=callback)
def info(self, section_name=None, callback=None):
args = ('INFO', )
if section_name:
args += (section_name, )
self.execute_command(*args, callback=callback)
def echo(self, value, callback=None):
self.execute_command('ECHO', value, callback=callback)
def time(self, callback=None):
"""
Returns the server time as a 2-item tuple of ints:
(seconds since epoch, microseconds into this second).
"""
self.execute_command('TIME', callback=callback)
def select(self, db, callback=None):
self.selected_db = db
if self.connection.info.get('db', None) != db:
self.connection.info['db'] = db
self.execute_command('SELECT', '%s' % db, callback=callback)
elif callback:
callback(True)
def shutdown(self, callback=None):
self.execute_command('SHUTDOWN', callback=callback)
def save(self, callback=None):
self.execute_command('SAVE', callback=callback)
def bgsave(self, callback=None):
self.execute_command('BGSAVE', callback=callback)
def lastsave(self, callback=None):
self.execute_command('LASTSAVE', callback=callback)
def keys(self, pattern='*', callback=None):
self.execute_command('KEYS', pattern, callback=callback)
def auth(self, password, callback=None):
self.password = password
if self.connection.info.get('pass', None) != password:
self.connection.info['pass'] = password
self.execute_command('AUTH', password, callback=callback)
elif callback:
callback(True)
### BASIC KEY COMMANDS
def append(self, key, value, callback=None):
self.execute_command('APPEND', key, value, callback=callback)
def getrange(self, key, start, end, callback=None):
"""
Returns the substring of the string value stored at ``key``,
determined by the offsets ``start`` and ``end`` (both are inclusive)
"""
self.execute_command('GETRANGE', key, start, end, callback=callback)
def expire(self, key, ttl, callback=None):
self.execute_command('EXPIRE', key, ttl, callback=callback)
def expireat(self, key, when, callback=None):
"""
Sets an expire flag on ``key``. ``when`` can be represented
as an integer indicating unix time or a Python datetime.datetime object.
"""
if isinstance(when, datetime.datetime):
when = int(mod_time.mktime(when.timetuple()))
self.execute_command('EXPIREAT', key, when, callback=callback)
def ttl(self, key, callback=None):
self.execute_command('TTL', key, callback=callback)
def type(self, key, callback=None):
self.execute_command('TYPE', key, callback=callback)
def randomkey(self, callback=None):
self.execute_command('RANDOMKEY', callback=callback)
def rename(self, src, dst, callback=None):
self.execute_command('RENAME', src, dst, callback=callback)
def renamenx(self, src, dst, callback=None):
self.execute_command('RENAMENX', src, dst, callback=callback)
def move(self, key, db, callback=None):
self.execute_command('MOVE', key, db, callback=callback)
def persist(self, key, callback=None):
self.execute_command('PERSIST', key, callback=callback)
def pexpire(self, key, time, callback=None):
"""
Set an expire flag on key ``key`` for ``time`` milliseconds.
``time`` can be represented by an integer or a Python timedelta
object.
"""
if isinstance(time, datetime.timedelta):
ms = int(time.microseconds / 1000)
time = time.seconds + time.days * 24 * 3600 * 1000 + ms
self.execute_command('PEXPIRE', key, time, callback=callback)
def pexpireat(self, key, when, callback=None):
"""
Set an expire flag on key ``key``. ``when`` can be represented
as an integer representing unix time in milliseconds (unix time * 1000)
or a Python datetime.datetime object.
"""
if isinstance(when, datetime.datetime):
ms = int(when.microsecond / 1000)
when = int(mod_time.mktime(when.timetuple())) * 1000 + ms
self.execute_command('PEXPIREAT', key, when, callback=callback)
def pttl(self, key, callback=None):
"Returns the number of milliseconds until the key will expire"
self.execute_command('PTTL', key, callback=callback)
def substr(self, key, start, end, callback=None):
self.execute_command('SUBSTR', key, start, end, callback=callback)
def delete(self, *keys, **kwargs):
self.execute_command('DEL', *keys, callback=kwargs.get('callback'))
def set(self, key, value, expire=None, pexpire=None,
only_if_not_exists=False, only_if_exists=False, callback=None):
args = []
if expire is not None:
args.extend(("EX", expire))
if pexpire is not None:
args.extend(("PX", pexpire))
if only_if_not_exists and only_if_exists:
raise ValueError("only_if_not_exists and only_if_exists "
"cannot be true simultaneously")
if only_if_not_exists:
args.append("NX")
if only_if_exists:
args.append("XX")
self.execute_command('SET', key, value, *args, callback=callback)
def setex(self, key, ttl, value, callback=None):
self.execute_command('SETEX', key, ttl, value, callback=callback)
def setnx(self, key, value, callback=None):
self.execute_command('SETNX', key, value, callback=callback)
def setrange(self, key, offset, value, callback=None):
self.execute_command('SETRANGE', key, offset, value, callback=callback)
def strlen(self, key, callback=None):
self.execute_command('STRLEN', key, callback=callback)
def mset(self, mapping, callback=None):
items = [i for k, v in mapping.items() for i in (k, v)]
self.execute_command('MSET', *items, callback=callback)
def msetnx(self, mapping, callback=None):
items = [i for k, v in mapping.items() for i in (k, v)]
self.execute_command('MSETNX', *items, callback=callback)
def get(self, key, callback=None):
self.execute_command('GET', key, callback=callback)
def mget(self, keys, callback=None):
self.execute_command('MGET', *keys, callback=callback)
def getset(self, key, value, callback=None):
self.execute_command('GETSET', key, value, callback=callback)
def exists(self, key, callback=None):
self.execute_command('EXISTS', key, callback=callback)
def sort(self, key, start=None, num=None, by=None, get=None, desc=False,
alpha=False, store=None, callback=None):
if ((start is not None and num is None) or
(num is not None and start is None)):
raise ValueError("``start`` and ``num`` must both be specified")
tokens = [key]
if by is not None:
tokens.append('BY')
tokens.append(by)
if start is not None and num is not None:
tokens.append('LIMIT')
tokens.append(start)
tokens.append(num)
if get is not None:
tokens.append('GET')
tokens.append(get)
if desc:
tokens.append('DESC')
if alpha:
tokens.append('ALPHA')
if store is not None:
tokens.append('STORE')
tokens.append(store)
self.execute_command('SORT', *tokens, callback=callback)
def getbit(self, key, offset, callback=None):
self.execute_command('GETBIT', key, offset, callback=callback)
def setbit(self, key, offset, value, callback=None):
self.execute_command('SETBIT', key, offset, value, callback=callback)
def bitcount(self, key, start=None, end=None, callback=None):
args = [a for a in (key, start, end) if a is not None]
kwargs = {'callback': callback}
self.execute_command('BITCOUNT', *args, **kwargs)
def bitop(self, operation, dest, *keys, **kwargs):
"""
Perform a bitwise operation using ``operation`` between ``keys`` and
store the result in ``dest``.
"""
kwargs = {'callback': kwargs.get('callback', None)}
self.execute_command('BITOP', operation, dest, *keys, **kwargs)
### COUNTERS COMMANDS
def incr(self, key, callback=None):
self.execute_command('INCR', key, callback=callback)
def decr(self, key, callback=None):
self.execute_command('DECR', key, callback=callback)
def incrby(self, key, amount, callback=None):
self.execute_command('INCRBY', key, amount, callback=callback)
def incrbyfloat(self, key, amount=1.0, callback=None):
self.execute_command('INCRBYFLOAT', key, amount, callback=callback)
def decrby(self, key, amount, callback=None):
self.execute_command('DECRBY', key, amount, callback=callback)
### LIST COMMANDS
def blpop(self, keys, timeout=0, callback=None):
tokens = to_list(keys)
tokens.append(timeout)
self.execute_command('BLPOP', *tokens, callback=callback)
def brpop(self, keys, timeout=0, callback=None):
tokens = to_list(keys)
tokens.append(timeout)
self.execute_command('BRPOP', *tokens, callback=callback)
def brpoplpush(self, src, dst, timeout=1, callback=None):
tokens = [src, dst, timeout]
self.execute_command('BRPOPLPUSH', *tokens, callback=callback)
def lindex(self, key, index, callback=None):
self.execute_command('LINDEX', key, index, callback=callback)
def llen(self, key, callback=None):
self.execute_command('LLEN', key, callback=callback)
def lrange(self, key, start, end, callback=None):
self.execute_command('LRANGE', key, start, end, callback=callback)
def lrem(self, key, value, num=0, callback=None):
self.execute_command('LREM', key, num, value, callback=callback)
def lset(self, key, index, value, callback=None):
self.execute_command('LSET', key, index, value, callback=callback)
def ltrim(self, key, start, end, callback=None):
self.execute_command('LTRIM', key, start, end, callback=callback)
def lpush(self, key, *values, **kwargs):
callback = kwargs.get('callback', None)
self.execute_command('LPUSH', key, *values, callback=callback)
def lpushx(self, key, value, callback=None):
self.execute_command('LPUSHX', key, value, callback=callback)
def linsert(self, key, where, refvalue, value, callback=None):
self.execute_command('LINSERT', key, where, refvalue, value,
callback=callback)
def rpush(self, key, *values, **kwargs):
callback = kwargs.get('callback', None)
self.execute_command('RPUSH', key, *values, callback=callback)
def rpushx(self, key, value, **kwargs):
"Push ``value`` onto the tail of the list ``name`` if ``name`` exists"
callback = kwargs.get('callback', None)
self.execute_command('RPUSHX', key, value, callback=callback)
def lpop(self, key, callback=None):
self.execute_command('LPOP', key, callback=callback)
def rpop(self, key, callback=None):
self.execute_command('RPOP', key, callback=callback)
def rpoplpush(self, src, dst, callback=None):
self.execute_command('RPOPLPUSH', src, dst, callback=callback)
### SET COMMANDS
def sadd(self, key, *values, **kwargs):
callback = kwargs.get('callback', None)
self.execute_command('SADD', key, *values, callback=callback)
def srem(self, key, *values, **kwargs):
callback = kwargs.get('callback', None)
self.execute_command('SREM', key, *values, callback=callback)
def scard(self, key, callback=None):
self.execute_command('SCARD', key, callback=callback)
def spop(self, key, callback=None):
self.execute_command('SPOP', key, callback=callback)
def smove(self, src, dst, value, callback=None):
self.execute_command('SMOVE', src, dst, value, callback=callback)
def sismember(self, key, value, callback=None):
self.execute_command('SISMEMBER', key, value, callback=callback)
def smembers(self, key, callback=None):
self.execute_command('SMEMBERS', key, callback=callback)
def srandmember(self, key, number=None, callback=None):
if number:
self.execute_command('SRANDMEMBER', key, number, callback=callback)
else:
self.execute_command('SRANDMEMBER', key, callback=callback)
def sinter(self, keys, callback=None):
self.execute_command('SINTER', *keys, callback=callback)
def sdiff(self, keys, callback=None):
self.execute_command('SDIFF', *keys, callback=callback)
def sunion(self, keys, callback=None):
self.execute_command('SUNION', *keys, callback=callback)
def sinterstore(self, keys, dst, callback=None):
self.execute_command('SINTERSTORE', dst, *keys, callback=callback)
def sunionstore(self, keys, dst, callback=None):
self.execute_command('SUNIONSTORE', dst, *keys, callback=callback)
def sdiffstore(self, keys, dst, callback=None):
self.execute_command('SDIFFSTORE', dst, *keys, callback=callback)
### SORTED SET COMMANDS
def zadd(self, key, *score_value, **kwargs):
callback = kwargs.get('callback', None)
self.execute_command('ZADD', key, *score_value, callback=callback)
def zcard(self, key, callback=None):
self.execute_command('ZCARD', key, callback=callback)
def zincrby(self, key, value, amount, callback=None):
self.execute_command('ZINCRBY', key, amount, value, callback=callback)
def zrank(self, key, value, callback=None):
self.execute_command('ZRANK', key, value, callback=callback)
def zrevrank(self, key, value, callback=None):
self.execute_command('ZREVRANK', key, value, callback=callback)
def zrem(self, key, *values, **kwargs):
callback = kwargs.get('callback', None)
self.execute_command('ZREM', key, *values, callback=callback)
def zcount(self, key, start, end, callback=None):
self.execute_command('ZCOUNT', key, start, end, callback=callback)
def zscore(self, key, value, callback=None):
self.execute_command('ZSCORE', key, value, callback=callback)
def zrange(self, key, start, num, with_scores=True, callback=None):
tokens = [key, start, num]
if with_scores:
tokens.append('WITHSCORES')
self.execute_command('ZRANGE', *tokens, callback=callback)
def zrevrange(self, key, start, num, with_scores, callback=None):
tokens = [key, start, num]
if with_scores:
tokens.append('WITHSCORES')
self.execute_command('ZREVRANGE', *tokens, callback=callback)
def zrangebyscore(self, key, start, end, offset=None, limit=None,
with_scores=False, callback=None):
tokens = [key, start, end]
if offset is not None:
tokens.append('LIMIT')
tokens.append(offset)
tokens.append(limit)
if with_scores:
tokens.append('WITHSCORES')
self.execute_command('ZRANGEBYSCORE', *tokens, callback=callback)
def zrevrangebyscore(self, key, end, start, offset=None, limit=None,
with_scores=False, callback=None):
tokens = [key, end, start]
if offset is not None:
tokens.append('LIMIT')
tokens.append(offset)
tokens.append(limit)
if with_scores:
tokens.append('WITHSCORES')
self.execute_command('ZREVRANGEBYSCORE', *tokens, callback=callback)
def zremrangebyrank(self, key, start, end, callback=None):
self.execute_command('ZREMRANGEBYRANK', key, start, end,
callback=callback)
def zremrangebyscore(self, key, start, end, callback=None):
self.execute_command('ZREMRANGEBYSCORE', key, start, end,
callback=callback)
def zinterstore(self, dest, keys, aggregate=None, callback=None):
return self._zaggregate('ZINTERSTORE', dest, keys, aggregate, callback)
def zunionstore(self, dest, keys, aggregate=None, callback=None):
return self._zaggregate('ZUNIONSTORE', dest, keys, aggregate, callback)
def _zaggregate(self, command, dest, keys, aggregate, callback):
tokens = [dest, len(keys)]
if isinstance(keys, dict):
items = list(keys.items())
keys = [i[0] for i in items]
weights = [i[1] for i in items]
else:
weights = None
tokens.extend(keys)
if weights:
tokens.append('WEIGHTS')
tokens.extend(weights)
if aggregate:
tokens.append('AGGREGATE')
tokens.append(aggregate)
self.execute_command(command, *tokens, callback=callback)
### HASH COMMANDS
def hgetall(self, key, callback=None):
self.execute_command('HGETALL', key, callback=callback)
def hmset(self, key, mapping, callback=None):
items = [i for k, v in mapping.items() for i in (k, v)]
self.execute_command('HMSET', key, *items, callback=callback)