forked from IlyaSkriblovsky/txredisapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
txredisapi.py
2021 lines (1680 loc) · 61.3 KB
/
txredisapi.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
# Copyright 2009 Alexandre Fiori
# https://github.com/fiorix/txredisapi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# Credits:
# The Protocol class is an improvement of txRedis' protocol,
# by Dorian Raymer and Ludovico Magnocavallo.
#
# Sharding and Consistent Hashing implementation by Gleicon Moraes.
#
import bisect
import collections
import functools
import operator
import re
import types
import warnings
import zlib
import string
import hashlib
from twisted.internet import defer
from twisted.internet import protocol
from twisted.internet import reactor
from twisted.internet import task
from twisted.protocols import basic
from twisted.protocols import policies
from twisted.python import log
from twisted.python.failure import Failure
class RedisError(Exception):
pass
class ConnectionError(RedisError):
pass
class ResponseError(RedisError):
pass
class ScriptDoesNotExist(ResponseError):
pass
class NoScriptRunning(ResponseError):
pass
class InvalidResponse(RedisError):
pass
class InvalidData(RedisError):
pass
class WatchError(RedisError):
pass
def list_or_args(command, keys, args):
oldapi = bool(args)
try:
iter(keys)
if isinstance(keys, (str, unicode)):
raise TypeError
except TypeError:
oldapi = True
keys = [keys]
if oldapi:
warnings.warn(DeprecationWarning(
"Passing *args to redis.%s is deprecated. "
"Pass an iterable to ``keys`` instead" % command))
keys.extend(args)
return keys
# Possible first characters in a string containing an integer or a float.
_NUM_FIRST_CHARS = frozenset(string.digits + "+-.")
class MultiBulkStorage(object):
def __init__(self, parent=None):
self.items = None
self.pending = None
self.parent = parent
def set_pending(self, pending):
if self.pending is None:
if pending < 0:
self.items = None
self.pending = 0
else:
self.items = []
self.pending = pending
return self
else:
m = MultiBulkStorage(self)
m.set_pending(pending)
return m
def append(self, item):
self.pending -= 1
self.items.append(item)
class LineReceiver(protocol.Protocol, basic._PauseableMixin):
line_mode = 1
__buffer = ''
delimiter = '\r\n'
MAX_LENGTH = 16384
def clearLineBuffer(self):
b = self.__buffer
self.__buffer = ""
return b
def dataReceived(self, data, unpause=False):
if unpause is True:
if self.__buffer:
self.__buffer = data + self.__buffer
else:
self.__buffer += data
self.resumeProducing()
else:
self.__buffer = self.__buffer + data
while self.line_mode and not self.paused:
try:
line, self.__buffer = self.__buffer.split(self.delimiter, 1)
except ValueError:
if len(self.__buffer) > self.MAX_LENGTH:
line, self.__buffer = self.__buffer, ''
return self.lineLengthExceeded(line)
break
else:
linelength = len(line)
if linelength > self.MAX_LENGTH:
exceeded = line + self.__buffer
self.__buffer = ''
return self.lineLengthExceeded(exceeded)
why = self.lineReceived(line)
if why or self.transport and self.transport.disconnecting:
return why
else:
if not self.paused:
data = self.__buffer
self.__buffer = ''
if data:
return self.rawDataReceived(data)
def setLineMode(self, extra=''):
self.line_mode = 1
if extra:
self.pauseProducing()
reactor.callLater(0, self.dataReceived, extra, True)
def setRawMode(self):
self.line_mode = 0
def rawDataReceived(self, data):
raise NotImplementedError
def lineReceived(self, line):
raise NotImplementedError
def sendLine(self, line):
return self.transport.write(line + self.delimiter)
def lineLengthExceeded(self, line):
return self.transport.loseConnection()
class RedisProtocol(LineReceiver, policies.TimeoutMixin):
"""
Redis client protocol.
"""
def __init__(self, charset="utf-8", errors="strict"):
self.charset = charset
self.errors = errors
self.bulk_length = 0
self.bulk_buffer = []
self.post_proc = []
self.multi_bulk = MultiBulkStorage()
self.replyQueue = defer.DeferredQueue()
self.transactions = 0
self.inTransaction = False
self.unwatch_cc = lambda: ()
self.commit_cc = lambda: ()
self.script_hashes = set()
@defer.inlineCallbacks
def connectionMade(self):
if self.factory.dbid is not None:
try:
response = yield self.select(self.factory.dbid)
if isinstance(response, ResponseError):
raise response
except Exception, e:
self.factory.continueTrying = False
self.transport.loseConnection()
msg = "Redis error: could not set dbid=%s: %s" % \
(self.factory.dbid, str(e))
self.factory.connectionError(msg)
if self.factory.isLazy:
log.msg(msg)
defer.returnValue(None)
self.connected = 1
self.factory.addConnection(self)
def connectionLost(self, why):
self.connected = 0
self.script_hashes.clear()
self.factory.delConnection(self)
LineReceiver.connectionLost(self, why)
while self.replyQueue.waiting:
self.replyReceived(ConnectionError("Lost connection"))
def lineReceived(self, line):
"""
Reply types:
"-" error message
"+" single line status reply
":" integer number (protocol level only?)
"$" bulk data
"*" multi-bulk data
"""
if line:
self.resetTimeout()
token, data = line[0], line[1:]
else:
return
if token == "$": # bulk data
try:
self.bulk_length = long(data)
except ValueError:
self.replyReceived(InvalidResponse("Cannot convert data "
"'%s' to integer" % data))
else:
if self.bulk_length == -1:
self.bulk_length = 0
self.bulkDataReceived(None)
else:
self.bulk_length += 2 # 2 == \r\n
self.setRawMode()
elif token == "*": # multi-bulk data
try:
n = long(data)
except (TypeError, ValueError):
self.multi_bulk = MultiBulkStorage()
self.replyReceived(InvalidResponse("Cannot convert "
"multi-response header "
"'%s' to integer" % data))
else:
self.multi_bulk = self.multi_bulk.set_pending(n)
if n in (0, -1):
self.multiBulkDataReceived()
elif token == "+": # single line status
if data == "QUEUED":
self.transactions += 1
self.replyReceived(data)
else:
if self.multi_bulk.pending:
self.handleMultiBulkElement(data)
else:
self.replyReceived(data)
elif token == "-": # error
reply = ResponseError(data[4:] if data[:4] == "ERR" else data)
if self.multi_bulk.pending:
self.handleMultiBulkElement(reply)
else:
self.replyReceived(reply)
elif token == ":": # integer
try:
reply = int(data)
except ValueError:
reply = InvalidResponse(
"Cannot convert data '%s' to integer" % data)
if self.multi_bulk.pending:
self.handleMultiBulkElement(reply)
else:
self.replyReceived(reply)
def rawDataReceived(self, data):
"""
Process and dispatch to bulkDataReceived.
"""
if self.bulk_length:
data, rest = data[:self.bulk_length], data[self.bulk_length:]
self.bulk_length -= len(data)
else:
rest = ""
self.bulk_buffer.append(data)
if self.bulk_length == 0:
bulk_buffer = "".join(self.bulk_buffer)[:-2]
self.bulk_buffer = []
self.bulkDataReceived(bulk_buffer)
self.setLineMode(extra=rest)
def bulkDataReceived(self, data):
"""
Receipt of a bulk data element.
"""
el = None
if data is not None:
if data and data[0] in _NUM_FIRST_CHARS: # Most likely a number
try:
el = int(data) if data.find('.') == -1 else float(data)
except ValueError:
pass
if el is None:
try:
el = data.decode(self.charset)
except UnicodeDecodeError:
el = data
if self.multi_bulk.pending or self.multi_bulk.items:
self.handleMultiBulkElement(el)
else:
self.replyReceived(el)
def handleMultiBulkElement(self, element):
self.multi_bulk.append(element)
if not self.multi_bulk.pending:
self.multiBulkDataReceived()
def multiBulkDataReceived(self):
"""
Receipt of list or set of bulk data elements.
"""
while self.multi_bulk.parent and not self.multi_bulk.pending:
p = self.multi_bulk.parent
p.append(self.multi_bulk.items)
self.multi_bulk = p
if not self.multi_bulk.pending:
reply = self.multi_bulk.items
self.multi_bulk = MultiBulkStorage()
if self.inTransaction and reply is not None: # watch or multi has been called
if self.transactions > 0:
self.transactions -= len(reply) # multi: this must be an exec [commit] reply
if self.transactions == 0:
self.commit_cc()
if self.inTransaction: # watch but no multi: process the reply as usual
f = self.post_proc[1:]
if len(f) == 1 and callable(f[0]):
reply = f[0](reply)
else: # multi: this must be an exec reply
tmp = []
for f, v in zip(self.post_proc[1:], reply):
if callable(f):
tmp.append(f(v))
else:
tmp.append(v)
reply = tmp
self.post_proc = []
self.replyReceived(reply)
def replyReceived(self, reply):
"""
Complete reply received and ready to be pushed to the requesting
function.
"""
self.replyQueue.put(reply)
@staticmethod
def handle_reply(r):
if isinstance(r, Exception):
raise r
return r
def execute_command(self, *args, **kwargs):
if self.connected == 0:
raise ConnectionError("Not connected")
else:
cmds = []
cmd_template = "$%s\r\n%s\r\n"
for s in args:
if isinstance(s, str):
cmd = s
elif isinstance(s, unicode):
try:
cmd = s.encode(self.charset, self.errors)
except UnicodeEncodeError, e:
raise InvalidData(
"Error encoding unicode value '%s': %s" %
(repr(s), e))
elif isinstance(s, float):
try:
cmd = format(s, "f")
except NameError:
cmd = "%0.6f" % s
else:
cmd = str(s)
cmds.append(cmd_template % (len(cmd), cmd))
self.transport.write("*%s\r\n%s" % (len(cmds), "".join(cmds)))
r = self.replyQueue.get().addCallback(self.handle_reply)
if self.inTransaction:
self.post_proc.append(kwargs.get("post_proc"))
else:
if "post_proc" in kwargs:
f = kwargs["post_proc"]
if callable(f):
r.addCallback(f)
return r
##
# REDIS COMMANDS
##
# Connection handling
def quit(self):
"""
Close the connection
"""
self.factory.continueTrying = False
return self.execute_command("QUIT")
def auth(self, password):
"""
Simple password authentication if enabled
"""
return self.execute_command("AUTH", password)
def ping(self):
"""
Ping the server
"""
return self.execute_command("PING")
# Commands operating on all value types
def exists(self, key):
"""
Test if a key exists
"""
return self.execute_command("EXISTS", key)
def delete(self, keys, *args):
"""
Delete one or more keys
"""
keys = list_or_args("delete", keys, args)
return self.execute_command("DEL", *keys)
def type(self, key):
"""
Return the type of the value stored at key
"""
return self.execute_command("TYPE", key)
def keys(self, pattern="*"):
"""
Return all the keys matching a given pattern
"""
return self.execute_command("KEYS", pattern)
def randomkey(self):
"""
Return a random key from the key space
"""
return self.execute_command("RANDOMKEY")
def rename(self, oldkey, newkey):
"""
Rename the old key in the new one,
destroying the newname key if it already exists
"""
return self.execute_command("RENAME", oldkey, newkey)
def renamenx(self, oldkey, newkey):
"""
Rename the oldname key to newname,
if the newname key does not already exist
"""
return self.execute_command("RENAMENX", oldkey, newkey)
def dbsize(self):
"""
Return the number of keys in the current db
"""
return self.execute_command("DBSIZE")
def expire(self, key, time):
"""
Set a time to live in seconds on a key
"""
return self.execute_command("EXPIRE", key, time)
def persist(self, key):
"""
Remove the expire from a key
"""
return self.execute_command("PERSIST", key)
def ttl(self, key):
"""
Get the time to live in seconds of a key
"""
return self.execute_command("TTL", key)
def select(self, index):
"""
Select the DB with the specified index
"""
return self.execute_command("SELECT", index)
def move(self, key, dbindex):
"""
Move the key from the currently selected DB to the dbindex DB
"""
return self.execute_command("MOVE", key, dbindex)
def flush(self, all_dbs=False):
warnings.warn(DeprecationWarning(
"redis.flush() has been deprecated, "
"use redis.flushdb() or redis.flushall() instead"))
return all_dbs and self.flushall() or self.flushdb()
def flushdb(self):
"""
Remove all the keys from the currently selected DB
"""
return self.execute_command("FLUSHDB")
def flushall(self):
"""
Remove all the keys from all the databases
"""
return self.execute_command("FLUSHALL")
# Commands operating on string values
def set(self, key, value, preserve=False, getset=False):
"""
Set a key to a string value
"""
if preserve:
warnings.warn(DeprecationWarning(
"preserve option to 'set' is deprecated, "
"use redis.setnx() instead"))
return self.setnx(key, value)
if getset:
warnings.warn(DeprecationWarning(
"getset option to 'set' is deprecated, "
"use redis.getset() instead"))
return self.getset(key, value)
return self.execute_command("SET", key, value)
def get(self, key):
"""
Return the string value of the key
"""
return self.execute_command("GET", key)
def getbit(self, key, offset):
"""
Return the bit value at offset in the string value stored at key
"""
return self.execute_command("GETBIT", key, offset)
def getset(self, key, value):
"""
Set a key to a string returning the old value of the key
"""
return self.execute_command("GETSET", key, value)
def mget(self, keys, *args):
"""
Multi-get, return the strings values of the keys
"""
keys = list_or_args("mget", keys, args)
return self.execute_command("MGET", *keys)
def setbit(self, key, offset, value):
"""
Sets or clears the bit at offset in the string value stored at key
"""
if isinstance(value, bool):
value = int(value)
return self.execute_command("SETBIT", key, offset, value)
def setnx(self, key, value):
"""
Set a key to a string value if the key does not exist
"""
return self.execute_command("SETNX", key, value)
def setex(self, key, time, value):
"""
Set+Expire combo command
"""
return self.execute_command("SETEX", key, time, value)
def mset(self, mapping):
"""
Set the respective fields to the respective values.
HMSET replaces old values with new values.
"""
items = []
for pair in mapping.iteritems():
items.extend(pair)
return self.execute_command("MSET", *items)
def msetnx(self, mapping):
"""
Set multiple keys to multiple values in a single atomic
operation if none of the keys already exist
"""
items = []
for pair in mapping.iteritems():
items.extend(pair)
return self.execute_command("MSETNX", *items)
def bitop(self, operation, destkey, *srckeys):
"""
Perform a bitwise operation between multiple keys
and store the result in the destination key.
"""
srclen = len(srckeys)
if srclen == 0:
return defer.fail(RedisError("no ``srckeys`` specified"))
if isinstance(operation, (str, unicode)):
operation = operation.upper()
elif operation is operator.and_ or operation is operator.__and__:
operation = 'AND'
elif operation is operator.or_ or operation is operator.__or__:
operation = 'OR'
elif operation is operator.__xor__ or operation is operator.xor:
operation = 'XOR'
elif operation is operator.__not__ or operation is operator.not_:
operation = 'NOT'
if operation not in ('AND', 'OR', 'XOR', 'NOT'):
return defer.fail(InvalidData(
"Invalid operation: %s" % operation))
if operation == 'NOT' and srclen > 1:
return defer.fail(RedisError(
"bitop NOT takes only one ``srckey``"))
return self.execute_command('BITOP', operation, destkey, *srckeys)
def bitcount(self, key, start=None, end=None):
if (end is None and start is not None) or \
(start is None and end is not None):
raise RedisError("``start`` and ``end`` must both be specified")
if start is not None:
t = (start, end)
else:
t = ()
return self.execute_command("BITCOUNT", key, *t)
def incr(self, key, amount=1):
"""
Increment the integer value of key
"""
return self.execute_command("INCRBY", key, amount)
def incrby(self, key, amount):
"""
Increment the integer value of key by integer
"""
return self.incr(key, amount)
def decr(self, key, amount=1):
"""
Decrement the integer value of key
"""
return self.execute_command("DECRBY", key, amount)
def decrby(self, key, amount):
"""
Decrement the integer value of key by integer
"""
return self.decr(key, amount)
def append(self, key, value):
"""
Append the specified string to the string stored at key
"""
return self.execute_command("APPEND", key, value)
def substr(self, key, start, end=-1):
"""
Return a substring of a larger string
"""
return self.execute_command("SUBSTR", key, start, end)
# Commands operating on lists
def push(self, key, value, tail=False):
warnings.warn(DeprecationWarning(
"redis.push() has been deprecated, "
"use redis.lpush() or redis.rpush() instead"))
return tail and self.rpush(key, value) or self.lpush(key, value)
def rpush(self, key, value):
"""
Append an element to the tail of the List value at key
"""
if isinstance(value, tuple) or isinstance(value, list):
return self.execute_command("RPUSH", key, *value)
else:
return self.execute_command("RPUSH", key, value)
def lpush(self, key, value):
"""
Append an element to the head of the List value at key
"""
if isinstance(value, tuple) or isinstance(value, list):
return self.execute_command("LPUSH", key, *value)
else:
return self.execute_command("LPUSH", key, value)
def llen(self, key):
"""
Return the length of the List value at key
"""
return self.execute_command("LLEN", key)
def lrange(self, key, start, end):
"""
Return a range of elements from the List at key
"""
return self.execute_command("LRANGE", key, start, end)
def ltrim(self, key, start, end):
"""
Trim the list at key to the specified range of elements
"""
return self.execute_command("LTRIM", key, start, end)
def lindex(self, key, index):
"""
Return the element at index position from the List at key
"""
return self.execute_command("LINDEX", key, index)
def lset(self, key, index, value):
"""
Set a new value as the element at index position of the List at key
"""
return self.execute_command("LSET", key, index, value)
def lrem(self, key, count, value):
"""
Remove the first-N, last-N, or all the elements matching value
from the List at key
"""
return self.execute_command("LREM", key, count, value)
def pop(self, key, tail=False):
warnings.warn(DeprecationWarning(
"redis.pop() has been deprecated, "
"user redis.lpop() or redis.rpop() instead"))
return tail and self.rpop(key) or self.lpop(key)
def lpop(self, key):
"""
Return and remove (atomically) the first element of the List at key
"""
return self.execute_command("LPOP", key)
def rpop(self, key):
"""
Return and remove (atomically) the last element of the List at key
"""
return self.execute_command("RPOP", key)
def blpop(self, keys, timeout=0):
"""
Blocking LPOP
"""
if isinstance(keys, (str, unicode)):
keys = [keys]
else:
keys = list(keys)
keys.append(timeout)
return self.execute_command("BLPOP", *keys)
def brpop(self, keys, timeout=0):
"""
Blocking RPOP
"""
if isinstance(keys, (str, unicode)):
keys = [keys]
else:
keys = list(keys)
keys.append(timeout)
return self.execute_command("BRPOP", *keys)
def brpoplpush(self, source, destination, timeout = 0):
"""
Pop a value from a list, push it to another list and return
it; or block until one is available.
"""
return self.execute_command("BRPOPLPUSH", source, destination, timeout)
def rpoplpush(self, srckey, dstkey):
"""
Return and remove (atomically) the last element of the source
List stored at srckey and push the same element to the
destination List stored at dstkey
"""
return self.execute_command("RPOPLPUSH", srckey, dstkey)
def _make_set(self, result):
if isinstance(result, list):
return set(result)
return result
# Commands operating on sets
def sadd(self, key, members, *args):
"""
Add the specified member to the Set value at key
"""
members = list_or_args("sadd", members, args)
return self.execute_command("SADD", key, *members)
def srem(self, key, members, *args):
"""
Remove the specified member from the Set value at key
"""
members = list_or_args("srem", members, args)
return self.execute_command("SREM", key, *members)
def spop(self, key):
"""
Remove and return (pop) a random element from the Set value at key
"""
return self.execute_command("SPOP", key)
def smove(self, srckey, dstkey, member):
"""
Move the specified member from one Set to another atomically
"""
return self.execute_command(
"SMOVE", srckey, dstkey, member).addCallback(bool)
def scard(self, key):
"""
Return the number of elements (the cardinality) of the Set at key
"""
return self.execute_command("SCARD", key)
def sismember(self, key, value):
"""
Test if the specified value is a member of the Set at key
"""
return self.execute_command("SISMEMBER", key, value).addCallback(bool)
def sinter(self, keys, *args):
"""
Return the intersection between the Sets stored at key1, ..., keyN
"""
keys = list_or_args("sinter", keys, args)
return self.execute_command("SINTER", *keys).addCallback(
self._make_set)
def sinterstore(self, dstkey, keys, *args):
"""
Compute the intersection between the Sets stored
at key1, key2, ..., keyN, and store the resulting Set at dstkey
"""
keys = list_or_args("sinterstore", keys, args)
return self.execute_command("SINTERSTORE", dstkey, *keys)
def sunion(self, keys, *args):
"""
Return the union between the Sets stored at key1, key2, ..., keyN
"""
keys = list_or_args("sunion", keys, args)
return self.execute_command("SUNION", *keys).addCallback(
self._make_set)
def sunionstore(self, dstkey, keys, *args):
"""
Compute the union between the Sets stored
at key1, key2, ..., keyN, and store the resulting Set at dstkey
"""
keys = list_or_args("sunionstore", keys, args)
return self.execute_command("SUNIONSTORE", dstkey, *keys)
def sdiff(self, keys, *args):
"""
Return the difference between the Set stored at key1 and
all the Sets key2, ..., keyN
"""
keys = list_or_args("sdiff", keys, args)
return self.execute_command("SDIFF", *keys).addCallback(
self._make_set)
def sdiffstore(self, dstkey, keys, *args):
"""
Compute the difference between the Set key1 and all the
Sets key2, ..., keyN, and store the resulting Set at dstkey
"""
keys = list_or_args("sdiffstore", keys, args)
return self.execute_command("SDIFFSTORE", dstkey, *keys)
def smembers(self, key):
"""
Return all the members of the Set value at key
"""
return self.execute_command("SMEMBERS", key).addCallback(
self._make_set)
def srandmember(self, key):
"""
Return a random member of the Set value at key
"""
return self.execute_command("SRANDMEMBER", key)
# Commands operating on sorted zsets (sorted sets)
def zadd(self, key, score, member, *args):
"""
Add the specified member to the Sorted Set value at key
or update the score if it already exist
"""
if args:
# Args should be pairs (have even number of elements)
if len(args) % 2:
return defer.fail(InvalidData(
"Invalid number of arguments to ZADD"))
else:
l = [score, member]
l.extend(args)
args = l
else:
args = [score, member]
return self.execute_command("ZADD", key, *args)
def zrem(self, key, *args):
"""
Remove the specified member from the Sorted Set value at key
"""
return self.execute_command("ZREM", key, *args)
def zincr(self, key, member):
return self.zincrby(key, 1, member)
def zdecr(self, key, member):
return self.zincrby(key, -1, member)
def zincrby(self, key, increment, member):
"""
If the member already exists increment its score by increment,
otherwise add the member setting increment as score
"""
return self.execute_command("ZINCRBY", key, increment, member)
def zrank(self, key, member):
"""
Return the rank (or index) or member in the sorted set at key,
with scores being ordered from low to high
"""
return self.execute_command("ZRANK", key, member)
def zrevrank(self, key, member):
"""