-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.py
1051 lines (985 loc) · 26.9 KB
/
redis.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
#!/usr/bin/env python
""" redis.py - A client for the Redis daemon.
History:
- 20090603 fix missing errno import, add sunion and sunionstore commands,
generalize shebang (Jochen Kupperschmidt)
"""
__author__ = "Ludovico Magnocavallo <ludo\x40qix\x2eit>"
__copyright__ = "Copyright 2009, Ludovico Magnocavallo"
__license__ = "MIT"
__version__ = "0.5"
__revision__ = "$LastChangedRevision: 175 $"[22:-2]
__date__ = "$LastChangedDate: 2009-03-17 16:15:55 +0100 (Mar, 17 Mar 2009) $"[18:-2]
# TODO: Redis._get_multi_response
import socket
import decimal
import errno
BUFSIZE = 4096
class RedisError(Exception): pass
class ConnectionError(RedisError): pass
class ResponseError(RedisError): pass
class InvalidResponse(RedisError): pass
class InvalidData(RedisError): pass
class Redis(object):
"""The main Redis client.
"""
def __init__(self, host=None, port=None, timeout=None, db=None, nodelay=None, charset='utf8', errors='strict'):
self.host = host or 'localhost'
self.port = port or 6379
if timeout:
socket.setdefaulttimeout(timeout)
self.nodelay = nodelay
self.charset = charset
self.errors = errors
self._sock = None
self._fp = None
self.db = db
def _encode(self, s):
if isinstance(s, str):
return s
if isinstance(s, unicode):
try:
return s.encode(self.charset, self.errors)
except UnicodeEncodeError, e:
raise InvalidData("Error encoding unicode value '%s': %s" % (value.encode(self.charset, 'replace'), e))
return str(s)
def _write(self, s):
"""
>>> r = Redis(db=9)
>>> r.connect()
>>> r._sock.close()
>>> try:
... r._write('pippo')
... except ConnectionError, e:
... print e
Error 9 while writing to socket. Bad file descriptor.
>>>
>>>
"""
try:
self._sock.sendall(s)
except socket.error, e:
if e.args[0] == 32:
# broken pipe
self.disconnect()
raise ConnectionError("Error %s while writing to socket. %s." % tuple(e.args))
def _read(self):
try:
return self._fp.readline()
except socket.error, e:
if e.args and e.args[0] == errno.EAGAIN:
return
self.disconnect()
raise ConnectionError("Error %s while reading from socket. %s." % tuple(e.args))
if not data:
self.disconnect()
raise ConnectionError("Socket connection closed when reading.")
return data
def ping(self):
"""
>>> r = Redis(db=9)
>>> r.ping()
'PONG'
>>>
"""
self.connect()
self._write('PING\r\n')
return self.get_response()
def set(self, name, value, preserve=False, getset=False):
"""
>>> r = Redis(db=9)
>>> r.set('a', 'pippo')
'OK'
>>> r.set('a', u'pippo \u3235')
'OK'
>>> r.get('a')
u'pippo \u3235'
>>> r.set('b', 105.2)
'OK'
>>> r.set('b', 'xxx', preserve=True)
0
>>> r.get('b')
Decimal("105.2")
>>>
"""
self.connect()
# the following will raise an error for unicode values that can't be encoded to ascii
# we could probably add an 'encoding' arg to init, but then what do we do with get()?
# convert back to unicode? and what about ints, or pickled values?
if getset: command = 'GETSET'
elif preserve: command = 'SETNX'
else: command = 'SET'
value = self._encode(value)
self._write('%s %s %s\r\n%s\r\n' % (
command, name, len(value), value
))
return self.get_response()
def get(self, name):
"""
>>> r = Redis(db=9)
>>> r.set('a', 'pippo'), r.set('b', 15), r.set('c', ' \\r\\naaa\\nbbb\\r\\ncccc\\nddd\\r\\n '), r.set('d', '\\r\\n')
('OK', 'OK', 'OK', 'OK')
>>> r.get('a')
u'pippo'
>>> r.get('b')
15
>>> r.get('d')
u'\\r\\n'
>>> r.get('b')
15
>>> r.get('c')
u' \\r\\naaa\\nbbb\\r\\ncccc\\nddd\\r\\n '
>>> r.get('c')
u' \\r\\naaa\\nbbb\\r\\ncccc\\nddd\\r\\n '
>>> r.get('ajhsd')
>>>
"""
self.connect()
self._write('GET %s\r\n' % name)
return self.get_response()
def getset(self, name, value):
"""
>>> r = Redis(db=9)
>>> r.set('a', 'pippo')
'OK'
>>> r.getset('a', 2)
u'pippo'
>>>
"""
return self.set(name, value, getset=True)
def mget(self, *args):
"""
>>> r = Redis(db=9)
>>> r.set('a', 'pippo'), r.set('b', 15), r.set('c', '\\r\\naaa\\nbbb\\r\\ncccc\\nddd\\r\\n'), r.set('d', '\\r\\n')
('OK', 'OK', 'OK', 'OK')
>>> r.mget('a', 'b', 'c', 'd')
[u'pippo', 15, u'\\r\\naaa\\nbbb\\r\\ncccc\\nddd\\r\\n', u'\\r\\n']
>>>
"""
self.connect()
self._write('MGET %s\r\n' % ' '.join(args))
return self.get_response()
def incr(self, name, amount=1):
"""
>>> r = Redis(db=9)
>>> r.delete('a')
1
>>> r.incr('a')
1
>>> r.incr('a')
2
>>> r.incr('a', 2)
4
>>>
"""
self.connect()
if amount == 1:
self._write('INCR %s\r\n' % name)
else:
self._write('INCRBY %s %s\r\n' % (name, amount))
return self.get_response()
def decr(self, name, amount=1):
"""
>>> r = Redis(db=9)
>>> if r.get('a'):
... r.delete('a')
... else:
... print 1
1
>>> r.decr('a')
-1
>>> r.decr('a')
-2
>>> r.decr('a', 5)
-7
>>>
"""
self.connect()
if amount == 1:
self._write('DECR %s\r\n' % name)
else:
self._write('DECRBY %s %s\r\n' % (name, amount))
return self.get_response()
def exists(self, name):
"""
>>> r = Redis(db=9)
>>> r.exists('dsjhfksjdhfkdsjfh')
0
>>> r.set('a', 'a')
'OK'
>>> r.exists('a')
1
>>>
"""
self.connect()
self._write('EXISTS %s\r\n' % name)
return self.get_response()
def delete(self, name):
"""
>>> r = Redis(db=9)
>>> r.delete('dsjhfksjdhfkdsjfh')
0
>>> r.set('a', 'a')
'OK'
>>> r.delete('a')
1
>>> r.exists('a')
0
>>> r.delete('a')
0
>>>
"""
self.connect()
self._write('DEL %s\r\n' % name)
return self.get_response()
def get_type(self, name):
"""
>>> r = Redis(db=9)
>>> r.set('a', 3)
'OK'
>>> r.get_type('a')
'string'
>>> r.get_type('zzz')
>>>
"""
self.connect()
self._write('TYPE %s\r\n' % name)
res = self.get_response()
return None if res == 'none' else res
def keys(self, pattern):
"""
>>> r = Redis(db=9)
>>> r.flush()
'OK'
>>> r.set('a', 'a')
'OK'
>>> r.keys('a*')
[u'a']
>>> r.set('a2', 'a')
'OK'
>>> r.keys('a*')
[u'a', u'a2']
>>> r.delete('a2')
1
>>> r.keys('sjdfhskjh*')
[]
>>>
"""
self.connect()
self._write('KEYS %s\r\n' % pattern)
return self.get_response().split()
def randomkey(self):
"""
>>> r = Redis(db=9)
>>> r.set('a', 'a')
'OK'
>>> isinstance(r.randomkey(), str)
True
>>>
"""
#raise NotImplementedError("Implemented but buggy, do not use.")
self.connect()
self._write('RANDOMKEY\r\n')
return self.get_response()
def rename(self, src, dst, preserve=False):
"""
>>> r = Redis(db=9)
>>> try:
... r.rename('a', 'a')
... except ResponseError, e:
... print e
source and destination objects are the same
>>> r.rename('a', 'b')
'OK'
>>> try:
... r.rename('a', 'b')
... except ResponseError, e:
... print e
no such key
>>> r.set('a', 1)
'OK'
>>> r.rename('b', 'a', preserve=True)
0
>>>
"""
self.connect()
if preserve:
self._write('RENAMENX %s %s\r\n' % (src, dst))
return self.get_response()
else:
self._write('RENAME %s %s\r\n' % (src, dst))
return self.get_response() #.strip()
def dbsize(self):
"""
>>> r = Redis(db=9)
>>> type(r.dbsize())
<type 'int'>
>>>
"""
self.connect()
self._write('DBSIZE\r\n')
return self.get_response()
def ttl(self, name):
"""
>>> r = Redis(db=9)
>>> r.ttl('a')
-1
>>> r.expire('a', 10)
1
>>> r.ttl('a')
10
>>> r.expire('a', 0)
0
>>>
"""
self.connect()
self._write('TTL %s\r\n' % name)
return self.get_response()
def expire(self, name, time):
"""
>>> r = Redis(db=9)
>>> r.set('a', 1)
'OK'
>>> r.expire('a', 1)
1
>>> r.expire('zzzzz', 1)
0
>>>
"""
self.connect()
self._write('EXPIRE %s %s\r\n' % (name, time))
return self.get_response()
def push(self, name, value, tail=False):
"""
>>> r = Redis(db=9)
>>> r.delete('l')
1
>>> r.push('l', 'a')
'OK'
>>> r.set('a', 'a')
'OK'
>>> try:
... r.push('a', 'a')
... except ResponseError, e:
... print e
Operation against a key holding the wrong kind of value
>>>
"""
self.connect()
value = self._encode(value)
self._write('%s %s %s\r\n%s\r\n' % (
'LPUSH' if tail else 'RPUSH', name, len(value), value
))
return self.get_response()
def llen(self, name):
"""
>>> r = Redis(db=9)
>>> r.delete('l')
1
>>> r.push('l', 'a')
'OK'
>>> r.llen('l')
1
>>> r.push('l', 'a')
'OK'
>>> r.llen('l')
2
>>>
"""
self.connect()
self._write('LLEN %s\r\n' % name)
return self.get_response()
def lrange(self, name, start, end):
"""
>>> r = Redis(db=9)
>>> r.delete('l')
1
>>> r.lrange('l', 0, 1)
[]
>>> r.push('l', 'aaa')
'OK'
>>> r.lrange('l', 0, 1)
[u'aaa']
>>> r.push('l', 'bbb')
'OK'
>>> r.lrange('l', 0, 0)
[u'aaa']
>>> r.lrange('l', 0, 1)
[u'aaa', u'bbb']
>>> r.lrange('l', -1, 0)
[]
>>> r.lrange('l', -1, -1)
[u'bbb']
>>>
"""
self.connect()
self._write('LRANGE %s %s %s\r\n' % (name, start, end))
return self.get_response()
def ltrim(self, name, start, end):
"""
>>> r = Redis(db=9)
>>> r.delete('l')
1
>>> try:
... r.ltrim('l', 0, 1)
... except ResponseError, e:
... print e
no such key
>>> r.push('l', 'aaa')
'OK'
>>> r.push('l', 'bbb')
'OK'
>>> r.push('l', 'ccc')
'OK'
>>> r.ltrim('l', 0, 1)
'OK'
>>> r.llen('l')
2
>>> r.ltrim('l', 99, 95)
'OK'
>>> r.llen('l')
0
>>>
"""
self.connect()
self._write('LTRIM %s %s %s\r\n' % (name, start, end))
return self.get_response()
def lindex(self, name, index):
"""
>>> r = Redis(db=9)
>>> res = r.delete('l')
>>> r.lindex('l', 0)
>>> r.push('l', 'aaa')
'OK'
>>> r.lindex('l', 0)
u'aaa'
>>> r.lindex('l', 2)
>>> r.push('l', 'ccc')
'OK'
>>> r.lindex('l', 1)
u'ccc'
>>> r.lindex('l', -1)
u'ccc'
>>>
"""
self.connect()
self._write('LINDEX %s %s\r\n' % (name, index))
return self.get_response()
def pop(self, name, tail=False):
"""
>>> r = Redis(db=9)
>>> r.delete('l')
1
>>> r.pop('l')
>>> r.push('l', 'aaa')
'OK'
>>> r.push('l', 'bbb')
'OK'
>>> r.pop('l')
u'aaa'
>>> r.pop('l')
u'bbb'
>>> r.pop('l')
>>> r.push('l', 'aaa')
'OK'
>>> r.push('l', 'bbb')
'OK'
>>> r.pop('l', tail=True)
u'bbb'
>>> r.pop('l')
u'aaa'
>>> r.pop('l')
>>>
"""
self.connect()
self._write('%s %s\r\n' % ('RPOP' if tail else 'LPOP', name))
return self.get_response()
def lset(self, name, index, value):
"""
>>> r = Redis(db=9)
>>> r.delete('l')
1
>>> try:
... r.lset('l', 0, 'a')
... except ResponseError, e:
... print e
no such key
>>> r.push('l', 'aaa')
'OK'
>>> try:
... r.lset('l', 1, 'a')
... except ResponseError, e:
... print e
index out of range
>>> r.lset('l', 0, 'bbb')
'OK'
>>> r.lrange('l', 0, 1)
[u'bbb']
>>>
"""
self.connect()
value = self._encode(value)
self._write('LSET %s %s %s\r\n%s\r\n' % (
name, index, len(value), value
))
return self.get_response()
def lrem(self, name, value, num=0):
"""
>>> r = Redis(db=9)
>>> r.delete('l')
1
>>> r.push('l', 'aaa')
'OK'
>>> r.push('l', 'bbb')
'OK'
>>> r.push('l', 'aaa')
'OK'
>>> r.lrem('l', 'aaa')
2
>>> r.lrange('l', 0, 10)
[u'bbb']
>>> r.push('l', 'aaa')
'OK'
>>> r.push('l', 'aaa')
'OK'
>>> r.lrem('l', 'aaa', 1)
1
>>> r.lrem('l', 'aaa', 1)
1
>>> r.lrem('l', 'aaa', 1)
0
>>>
"""
self.connect()
value = self._encode(value)
self._write('LREM %s %s %s\r\n%s\r\n' % (
name, num, len(value), value
))
return self.get_response()
def sort(self, name, by=None, get=None, start=None, num=None, desc=False, alpha=False):
"""
>>> r = Redis(db=9)
>>> r.delete('l')
1
>>> r.push('l', 'ccc')
'OK'
>>> r.push('l', 'aaa')
'OK'
>>> r.push('l', 'ddd')
'OK'
>>> r.push('l', 'bbb')
'OK'
>>> r.sort('l', alpha=True)
[u'aaa', u'bbb', u'ccc', u'ddd']
>>> r.delete('l')
1
>>> for i in range(1, 5):
... res = r.push('l', 1.0 / i)
>>> r.sort('l')
[Decimal("0.25"), Decimal("0.333333333333"), Decimal("0.5"), Decimal("1.0")]
>>> r.sort('l', desc=True)
[Decimal("1.0"), Decimal("0.5"), Decimal("0.333333333333"), Decimal("0.25")]
>>> r.sort('l', desc=True, start=2, num=1)
[Decimal("0.333333333333")]
>>> r.set('weight_0.5', 10)
'OK'
>>> r.sort('l', desc=True, by='weight_*')
[Decimal("0.5"), Decimal("1.0"), Decimal("0.333333333333"), Decimal("0.25")]
>>> for i in r.sort('l', desc=True):
... res = r.set('test_%s' % i, 100 - float(i))
>>> r.sort('l', desc=True, get='test_*')
[Decimal("99.0"), Decimal("99.5"), Decimal("99.6666666667"), Decimal("99.75")]
>>> r.sort('l', desc=True, by='weight_*', get='test_*')
[Decimal("99.5"), Decimal("99.0"), Decimal("99.6666666667"), Decimal("99.75")]
>>> r.sort('l', desc=True, by='weight_*', get='missing_*')
[None, None, None, None]
>>>
"""
stmt = ['SORT', name]
if by:
stmt.append("BY %s" % by)
if start and num:
stmt.append("LIMIT %s %s" % (start, num))
if get is None:
pass
elif isinstance(get, basestring):
stmt.append("GET %s" % get)
elif isinstance(get, list) or isinstance(get, tuple):
for g in get:
stmt.append("GET %s" % g)
else:
raise RedisError("Invalid parameter 'get' for Redis sort")
if desc:
stmt.append("DESC")
if alpha:
stmt.append("ALPHA")
self.connect()
self._write(' '.join(stmt + ["\r\n"]))
return self.get_response()
def sadd(self, name, value):
"""
>>> r = Redis(db=9)
>>> res = r.delete('s')
>>> r.sadd('s', 'a')
1
>>> r.sadd('s', 'b')
1
>>>
"""
self.connect()
value = self._encode(value)
self._write('SADD %s %s\r\n%s\r\n' % (
name, len(value), value
))
return self.get_response()
def srem(self, name, value):
"""
>>> r = Redis(db=9)
>>> r.delete('s')
1
>>> r.srem('s', 'aaa')
0
>>> r.sadd('s', 'b')
1
>>> r.srem('s', 'b')
1
>>> r.sismember('s', 'b')
0
>>>
"""
self.connect()
value = self._encode(value)
self._write('SREM %s %s\r\n%s\r\n' % (
name, len(value), value
))
return self.get_response()
def sismember(self, name, value):
"""
>>> r = Redis(db=9)
>>> r.delete('s')
1
>>> r.sismember('s', 'b')
0
>>> r.sadd('s', 'a')
1
>>> r.sismember('s', 'b')
0
>>> r.sismember('s', 'a')
1
>>>
"""
self.connect()
value = self._encode(value)
self._write('SISMEMBER %s %s\r\n%s\r\n' % (
name, len(value), value
))
return self.get_response()
def sinter(self, *args):
"""
>>> r = Redis(db=9)
>>> res = r.delete('s1')
>>> res = r.delete('s2')
>>> res = r.delete('s3')
>>> r.sadd('s1', 'a')
1
>>> r.sadd('s2', 'a')
1
>>> r.sadd('s3', 'b')
1
>>> try:
... r.sinter()
... except ResponseError, e:
... print e
wrong number of arguments
>>> try:
... r.sinter('l')
... except ResponseError, e:
... print e
Operation against a key holding the wrong kind of value
>>> r.sinter('s1', 's2', 's3')
set([])
>>> r.sinter('s1', 's2')
set([u'a'])
>>>
"""
self.connect()
self._write('SINTER %s\r\n' % ' '.join(args))
return set(self.get_response())
def sinterstore(self, dest, *args):
"""
>>> r = Redis(db=9)
>>> res = r.delete('s1')
>>> res = r.delete('s2')
>>> res = r.delete('s3')
>>> r.sadd('s1', 'a')
1
>>> r.sadd('s2', 'a')
1
>>> r.sadd('s3', 'b')
1
>>> r.sinterstore('s_s', 's1', 's2', 's3')
0
>>> r.sinterstore('s_s', 's1', 's2')
1
>>> r.smembers('s_s')
set([u'a'])
>>>
"""
self.connect()
self._write('SINTERSTORE %s %s\r\n' % (dest, ' '.join(args)))
return self.get_response()
def smembers(self, name):
"""
>>> r = Redis(db=9)
>>> r.delete('s')
1
>>> r.sadd('s', 'a')
1
>>> r.sadd('s', 'b')
1
>>> try:
... r.smembers('l')
... except ResponseError, e:
... print e
Operation against a key holding the wrong kind of value
>>> r.smembers('s')
set([u'a', u'b'])
>>>
"""
self.connect()
self._write('SMEMBERS %s\r\n' % name)
return set(self.get_response())
def sunion(self, *args):
"""
>>> r = Redis(db=9)
>>> res = r.delete('s1')
>>> res = r.delete('s2')
>>> res = r.delete('s3')
>>> r.sadd('s1', 'a')
1
>>> r.sadd('s2', 'a')
1
>>> r.sadd('s3', 'b')
1
>>> r.sunion('s1', 's2', 's3')
set([u'a', u'b'])
>>> r.sadd('s2', 'c')
1
>>> r.sunion('s1', 's2', 's3')
set([u'a', u'c', u'b'])
>>>
"""
self.connect()
self._write('SUNION %s\r\n' % ' '.join(args))
return set(self.get_response())
def sunionstore(self, dest, *args):
"""
>>> r = Redis(db=9)
>>> res = r.delete('s1')
>>> res = r.delete('s2')
>>> res = r.delete('s3')
>>> r.sadd('s1', 'a')
1
>>> r.sadd('s2', 'a')
1
>>> r.sadd('s3', 'b')
1
>>> r.sunionstore('s4', 's1', 's2', 's3')
2
>>> r.smembers('s4')
set([u'a', u'b'])
>>>
"""
self.connect()
self._write('SUNIONSTORE %s %s\r\n' % (dest, ' '.join(args)))
return self.get_response()
def select(self, db):
"""
>>> r = Redis(db=9)
>>> r.delete('a')
1
>>> r.select(10)
'OK'
>>> r.set('a', 1)
'OK'
>>> r.select(9)
'OK'
>>> r.get('a')
>>>
"""
self.connect()
self._write('SELECT %s\r\n' % db)
return self.get_response()
def move(self, name, db):
"""
>>> r = Redis(db=9)
>>> r.set('a', 'a')
'OK'
>>> r.select(10)
'OK'
>>> if r.get('a'):
... r.delete('a')
... else:
... print 1
1
>>> r.select(9)
'OK'
>>> r.move('a', 10)
1
>>> r.get('a')
>>> r.select(10)
'OK'
>>> r.get('a')
u'a'
>>> r.select(9)
'OK'
>>>
"""
self.connect()
self._write('MOVE %s %s\r\n' % (name, db))
return self.get_response()
def save(self, background=False):
"""
>>> r = Redis(db=9)
>>> r.save()
'OK'
>>> try:
... resp = r.save(background=True)
... except ResponseError, e:
... assert str(e) == 'background save already in progress', str(e)
... else:
... assert resp == 'OK'
>>>
"""
self.connect()
if background:
self._write('BGSAVE\r\n')
else:
self._write('SAVE\r\n')
return self.get_response()
def lastsave(self):
"""
>>> import time
>>> r = Redis(db=9)
>>> t = int(time.time())
>>> r.save()
'OK'
>>> r.lastsave() >= t
True
>>>
"""
self.connect()
self._write('LASTSAVE\r\n')
return self.get_response()
def flush(self, all_dbs=False):
"""
>>> r = Redis(db=9)
>>> r.flush()
'OK'
>>> # r.flush(all_dbs=True)
>>>
"""
self.connect()
self._write('%s\r\n' % ('FLUSHALL' if all_dbs else 'FLUSHDB'))
return self.get_response()
def info(self):
"""
>>> r = Redis(db=9)
>>> info = r.info()
>>> info and isinstance(info, dict)
True
>>> isinstance(info.get('connected_clients'), int)
True
>>>
"""
self.connect()
self._write('INFO\r\n')
info = dict()
for l in self.get_response().split('\r\n'):
if not l:
continue
k, v = l.split(':', 1)
info[k] = int(v) if v.isdigit() else v
return info
def auth(self, passwd):
self.connect()
self._write('AUTH %s\r\n' % passwd)
return self.get_response()
def get_response(self):
data = self._read().strip()
if not data:
self.disconnect()
raise ConnectionError("Socket closed on remote end")
c = data[0]
if c == '-':
raise ResponseError(data[5:] if data[:5] == '-ERR ' else data[1:])
if c == '+':
return data[1:]
if c == '*':
try:
num = int(data[1:])
except (TypeError, ValueError):
raise InvalidResponse("Cannot convert multi-response header '%s' to integer" % data)
result = list()
for i in range(num):
result.append(self._get_value())
return result
return self._get_value(data)
def _get_value(self, data=None):
data = data or self._read().strip()
if data == '$-1':
return None
try:
c, i = data[0], (int(data[1:]) if data.find('.') == -1 else float(data[1:]))
except ValueError:
raise InvalidResponse("Cannot convert data '%s' to integer" % data)
if c == ':':
return i
if c != '$':
raise InvalidResponse("Unkown response prefix for '%s'" % data)