forked from IlyaSkriblovsky/txredisapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
txredisapi.py
2505 lines (2104 loc) · 80.4 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 six
import bisect
import collections
import functools
import operator
import re
import warnings
import zlib
import string
import hashlib
import random
from twisted.internet import defer
from twisted.internet import protocol
from twisted.internet import reactor
from twisted.protocols import basic
from twisted.protocols import policies
from twisted.python import log
from twisted.python.failure import Failure
try:
import hiredis
except ImportError:
hiredis = None
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, six.string_types) or \
isinstance(keys, six.binary_type):
keys = [keys]
if not oldapi:
return keys
oldapi = True
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):
callLater = reactor.callLater
line_mode = 1
__buffer = six.b('')
delimiter = six.b('\r\n')
MAX_LENGTH = 16384
def clearLineBuffer(self):
b = self.__buffer
self.__buffer = six.b('')
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, six.b('')
return self.lineLengthExceeded(line)
break
else:
linelength = len(line)
if linelength > self.MAX_LENGTH:
exceeded = line + self.__buffer
self.__buffer = six.b('')
return self.lineLengthExceeded(exceeded)
if hasattr(line, 'decode'):
why = self.lineReceived(line.decode())
else:
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 = six.b('')
if data:
return self.rawDataReceived(data)
def setLineMode(self, extra=six.b('')):
self.line_mode = 1
if extra:
self.pauseProducing()
self.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):
if isinstance(line, six.text_type):
line = line.encode()
return self.transport.write(line + self.delimiter)
def lineLengthExceeded(self, line):
return self.transport.loseConnection()
class ReplyQueue(defer.DeferredQueue):
"""
Subclass defer.DeferredQueue to maintain consistency of
producers / consumers in light of defer.cancel
"""
def _cancelGet(self, d):
# rather than remove(d), the default twisted behavior
# we need to maintain an entry in the waiting list
# because the reply code assumes that every call
# to transport.write() generates a corresponding
# reply value in the queue.
# so we will just replace the cancelled deferred
# with a noop
i = self.waiting.index(d)
self.waiting[i] = defer.Deferred()
def _blocking_command(release_on_callback):
"""
Decorator used for marking protocol methods as `blocking` (methods that
block connection from being used for sending another requests)
release_on_callback means whether connection should be automatically
released when deferred returned by method is fired
"""
def decorator(method):
method._blocking = True
method._release_on_callback = release_on_callback
return method
return decorator
class BaseRedisProtocol(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 = bytearray()
self.post_proc = []
self.multi_bulk = MultiBulkStorage()
self.replyQueue = ReplyQueue()
self.transactions = 0
self.inTransaction = False
self.inMulti = False
self.unwatch_cc = lambda: ()
self.commit_cc = lambda: ()
self.script_hashes = set()
self.pipelining = False
self.pipelined_commands = []
self.pipelined_replies = []
@defer.inlineCallbacks
def connectionMade(self):
if self.factory.password is not None:
try:
response = yield self.auth(self.factory.password)
if isinstance(response, ResponseError):
raise response
except Exception as e:
self.factory.continueTrying = False
self.transport.loseConnection()
msg = "Redis error: could not auth: %s" % (str(e))
self.factory.connectionError(msg)
if self.factory.isLazy:
log.msg(msg)
defer.returnValue(None)
if self.factory.dbid is not None:
try:
response = yield self.select(self.factory.dbid)
if isinstance(response, ResponseError):
raise response
except Exception as 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 = int(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 = int(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.extend(data)
if self.bulk_length == 0:
bulk_buffer = self.bulk_buffer[:-2]
self.bulk_buffer = bytearray()
self.bulkDataReceived(bytes(bulk_buffer))
self.setLineMode(extra=rest)
def bulkDataReceived(self, data):
"""
Receipt of a bulk data element.
"""
el = None
if data is not None:
el = self.tryConvertData(data)
if self.multi_bulk.pending or self.multi_bulk.items:
self.handleMultiBulkElement(el)
else:
self.replyReceived(el)
def tryConvertData(self, data):
# The hiredis reader implicitly returns integers
if isinstance(data, six.integer_types):
return data
el = None
if self.factory.convertNumbers:
if data:
num_data = data
try:
if isinstance(data, six.binary_type):
num_data = data.decode()
except UnicodeError:
pass
else:
if num_data[0] in _NUM_FIRST_CHARS: # Most likely a number
try:
el = int(num_data) if num_data.find('.') == -1 \
else float(num_data)
except ValueError:
pass
if el is None:
el = data
if self.charset is not None:
try:
el = data.decode(self.charset)
except UnicodeDecodeError:
pass
except AttributeError:
el = data
return 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()
reply = self.handleTransactionData(reply)
self.replyReceived(reply)
def handleTransactionData(self, reply):
if self.inTransaction and isinstance(reply, list):
# watch or multi has been called
if self.transactions > 0:
# multi: this must be an exec [commit] reply
self.transactions -= len(reply)
if self.transactions == 0:
self.commit_cc()
if not self.inTransaction: # 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 = []
return 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 _encode_value(self, arg):
if isinstance(arg, six.binary_type):
return arg
elif isinstance(arg, six.text_type):
if self.charset is None:
try:
return arg.encode()
except UnicodeError:
pass
raise InvalidData("Encoding charset was not specified")
try:
return arg.encode(self.charset, self.errors)
except UnicodeEncodeError as e:
raise InvalidData(
"Error encoding unicode value '%s': %s" %
(repr(arg), e))
elif isinstance(arg, float):
return format(arg, "f").encode()
elif isinstance(arg, bytearray):
return bytes(arg)
else:
return str(arg).format().encode()
def _build_command(self, *args, **kwargs):
# Build the redis command.
cmds = bytearray()
cmd_count = 0
for s in args:
cmd = self._encode_value(s)
cmds.extend(six.b("$"))
for token in self._encode_value(len(cmd)), cmd:
cmds.extend(token)
cmds.extend(six.b("\r\n"))
cmd_count += 1
command = bytes(six.b("").join(
[six.b("*"), self._encode_value(cmd_count), six.b("\r\n")]) + cmds)
if not isinstance(command, six.binary_type):
command = command.encode()
return command
def execute_command(self, *args, **kwargs):
if self.connected == 0:
raise ConnectionError("Not connected")
else:
command = self._build_command(*args, **kwargs)
# When pipelining, buffer this command into our list of
# pipelined commands. Otherwise, write the command immediately.
if self.pipelining:
self.pipelined_commands.append(command)
else:
self.transport.write(command)
# Return deferred that will contain the result of this command.
# Note: when using pipelining, this deferred will NOT return
# until after execute_pipeline is called.
r = self.replyQueue.get().addCallback(self.handle_reply)
# When pipelining, we need to keep track of the deferred replies
# so that we can wait for them in a DeferredList when
# execute_pipeline is called.
if self.pipelining:
self.pipelined_replies.append(r)
if self.inMulti:
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)
@staticmethod
def _build_scan_args(cursor, pattern, count):
"""
Construct arguments list for SCAN, SSCAN, HSCAN, ZSCAN commands
"""
args = [cursor]
if pattern is not None:
args.extend(("MATCH", pattern))
if count is not None:
args.extend(("COUNT", count))
return args
def scan(self, cursor=0, pattern=None, count=None):
"""
Incrementally iterate the keys in database
"""
args = self._build_scan_args(cursor, pattern, count)
return self.execute_command("SCAN", *args)
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")
def time(self):
"""
Returns the current server time as a two items lists: a Unix timestamp
and the amount of microseconds already elapsed in the current second
"""
return self.execute_command("TIME")
# Commands operating on string values
def set(self, key, value, expire=None, pexpire=None,
only_if_not_exists=False, only_if_exists=False):
"""
Set a key to a string value
"""
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 RedisError("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")
return self.execute_command("SET", key, value, *args)
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 six.iteritems(mapping):
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 six.iteritems(mapping):
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, six.string_types):
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)
@_blocking_command(release_on_callback=True)
def blpop(self, keys, timeout=0):
"""
Blocking LPOP
"""
if isinstance(keys, six.string_types):
keys = [keys]
else:
keys = list(keys)
keys.append(timeout)
return self.execute_command("BLPOP", *keys)
@_blocking_command(release_on_callback=True)
def brpop(self, keys, timeout=0):
"""
Blocking RPOP
"""
if isinstance(keys, six.string_types):
keys = [keys]
else:
keys = list(keys)
keys.append(timeout)
return self.execute_command("BRPOP", *keys)
@_blocking_command(release_on_callback=True)
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