]>
git.saurik.com Git - redis.git/blob - client-libraries/python/redis.py
3 """ redis.py - A client for the Redis daemon.
7 __author__
= "Ludovico Magnocavallo <ludo\x40qix\x2eit>"
8 __copyright__
= "Copyright 2009, Ludovico Magnocavallo"
11 __revision__
= "$LastChangedRevision: 175 $"[22:-2]
12 __date__
= "$LastChangedDate: 2009-03-17 16:15:55 +0100 (Mar, 17 Mar 2009) $"[18:-2]
15 # TODO: Redis._get_multi_response
24 class RedisError(Exception): pass
25 class ConnectionError(RedisError
): pass
26 class ResponseError(RedisError
): pass
27 class InvalidResponse(RedisError
): pass
28 class InvalidData(RedisError
): pass
32 """The main Redis client.
35 def __init__(self
, host
=None, port
=None, timeout
=None):
36 self
.host
= host
or 'localhost'
37 self
.port
= port
or 6379
39 socket
.setdefaulttimeout(timeout
)
50 ... except ConnectionError, e:
52 Error 9 while writing to socket. Bad file descriptor.
58 except socket
.error
, e
:
62 raise ConnectionError("Error %s while writing to socket. %s." % tuple(e
.args
))
66 return self
._fp
.readline()
67 except socket
.error
, e
:
68 if e
.args
and e
.args
[0] == errno
.EAGAIN
:
71 raise ConnectionError("Error %s while reading from socket. %s." % tuple(e
.args
))
74 raise ConnectionError("Socket connection closed when reading.")
85 self
._write
('PING\r\n')
86 return self
.get_response()
88 def set(self
, name
, value
, preserve
=False):
91 >>> r.set('a', 'pippo')
94 ... r.set('a', u'pippo \u3235')
95 ... except InvalidData, e:
97 Error encoding unicode value for key 'a': 'ascii' codec can't encode character u'\u3235' in position 15: ordinal not in range(128).
100 >>> r.set('b', 'xxx', preserve=True)
107 # the following will raise an error for unicode values that can't be encoded to ascii
108 # we could probably add an 'encoding' arg to init, but then what do we do with get()?
109 # convert back to unicode? and what about ints, or pickled values?
111 value
= value
if isinstance(value
, basestring
) else str(value
)
112 self
._write
('%s %s %s\r\n%s\r\n' % (
113 'SETNX' if preserve
else 'SET', name
, len(value
), value
115 except UnicodeEncodeError, e
:
116 raise InvalidData("Error encoding unicode value for key '%s': %s." % (name
, e
))
117 return self
.get_response()
122 >>> r.set('a', 'pippo'), r.set('b', 15), r.set('c', '\\r\\naaa\\nbbb\\r\\ncccc\\nddd\\r\\n'), r.set('d', '\\r\\n')
123 ('OK', 'OK', 'OK', 'OK')
133 '\\r\\naaa\\nbbb\\r\\ncccc\\nddd\\r\\n'
135 '\\r\\naaa\\nbbb\\r\\ncccc\\nddd\\r\\n'
140 self
._write
('GET %s\r\n' % name
)
141 return self
.get_response()
143 def mget(self
, *args
):
146 >>> r.set('a', 'pippo'), r.set('b', 15), r.set('c', '\\r\\naaa\\nbbb\\r\\ncccc\\nddd\\r\\n'), r.set('d', '\\r\\n')
147 ('OK', 'OK', 'OK', 'OK')
148 >>> r.mget('a', 'b', 'c', 'd')
149 ['pippo', '15', '\\r\\naaa\\nbbb\\r\\ncccc\\nddd\\r\\n', '\\r\\n']
153 self
._write
('MGET %s\r\n' % ' '.join(args
))
154 return self
.get_response()
156 def incr(self
, name
, amount
=1):
171 self
._write
('INCR %s\r\n' % name
)
173 self
._write
('INCRBY %s %s\r\n' % (name
, amount
))
174 return self
.get_response()
176 def decr(self
, name
, amount
=1):
194 self
._write
('DECR %s\r\n' % name
)
196 self
._write
('DECRBY %s %s\r\n' % (name
, amount
))
197 return self
.get_response()
199 def exists(self
, name
):
202 >>> r.exists('dsjhfksjdhfkdsjfh')
211 self
._write
('EXISTS %s\r\n' % name
)
212 return self
.get_response()
214 def delete(self
, name
):
217 >>> r.delete('dsjhfksjdhfkdsjfh')
230 self
._write
('DEL %s\r\n' % name
)
231 return self
.get_response()
233 def key_type(self
, name
):
238 self
._write
('TYPE %s\r\n' % name
)
239 return self
.get_response()
241 def keys(self
, pattern
):
256 >>> r.keys('sjdfhskjh*')
261 self
._write
('KEYS %s\r\n' % pattern
)
262 return self
.get_response().split()
269 >>> isinstance(r.randomkey(), str)
273 #raise NotImplementedError("Implemented but buggy, do not use.")
275 self
._write
('RANDOMKEY\r\n')
276 return self
.get_response()
278 def rename(self
, src
, dst
, preserve
=False):
282 ... r.rename('a', 'a')
283 ... except ResponseError, e:
285 source and destination objects are the same
286 >>> r.rename('a', 'b')
289 ... r.rename('a', 'b')
290 ... except ResponseError, e:
295 >>> r.rename('b', 'a', preserve=True)
301 self
._write
('RENAMENX %s %s\r\n' % (src
, dst
))
302 return self
.get_response()
304 self
._write
('RENAME %s %s\r\n' % (src
, dst
))
305 return self
.get_response().strip()
307 def push(self
, name
, value
, tail
=False):
318 ... except ResponseError, e:
320 Operation against a key holding the wrong kind of value
324 # same considerations on unicode as in set() apply here
326 value
= value
if isinstance(value
, basestring
) else str(value
)
327 self
._write
('%s %s %s\r\n%s\r\n' % (
328 'LPUSH' if tail
else 'RPUSH', name
, len(value
), value
330 except UnicodeEncodeError, e
:
331 raise InvalidData("Error encoding unicode value for element in list '%s': %s." % (name
, e
))
332 return self
.get_response()
334 def llen(self
, name
):
350 self
._write
('LLEN %s\r\n' % name
)
351 return self
.get_response()
353 def lrange(self
, name
, start
, end
):
358 >>> r.lrange('l', 0, 1)
360 >>> r.push('l', 'aaa')
362 >>> r.lrange('l', 0, 1)
364 >>> r.push('l', 'bbb')
366 >>> r.lrange('l', 0, 0)
368 >>> r.lrange('l', 0, 1)
370 >>> r.lrange('l', -1, 0)
372 >>> r.lrange('l', -1, -1)
377 self
._write
('LRANGE %s %s %s\r\n' % (name
, start
, end
))
378 return self
.get_response()
380 def ltrim(self
, name
, start
, end
):
386 ... r.ltrim('l', 0, 1)
387 ... except ResponseError, e:
390 >>> r.push('l', 'aaa')
392 >>> r.push('l', 'bbb')
394 >>> r.push('l', 'ccc')
396 >>> r.ltrim('l', 0, 1)
400 >>> r.ltrim('l', 99, 95)
407 self
._write
('LTRIM %s %s %s\r\n' % (name
, start
, end
))
408 return self
.get_response()
410 def lindex(self
, name
, index
):
413 >>> res = r.delete('l')
415 >>> r.push('l', 'aaa')
420 >>> r.push('l', 'ccc')
424 >>> r.lindex('l', -1)
429 self
._write
('LINDEX %s %s\r\n' % (name
, index
))
430 return self
.get_response()
432 def pop(self
, name
, tail
=False):
438 >>> r.push('l', 'aaa')
440 >>> r.push('l', 'bbb')
447 >>> r.push('l', 'aaa')
449 >>> r.push('l', 'bbb')
451 >>> r.pop('l', tail=True)
459 self
._write
('%s %s\r\n' % ('RPOP' if tail
else 'LPOP', name
))
460 return self
.get_response()
462 def lset(self
, name
, index
, value
):
468 ... r.lset('l', 0, 'a')
469 ... except ResponseError, e:
472 >>> r.push('l', 'aaa')
475 ... r.lset('l', 1, 'a')
476 ... except ResponseError, e:
479 >>> r.lset('l', 0, 'bbb')
481 >>> r.lrange('l', 0, 1)
487 value
= value
if isinstance(value
, basestring
) else str(value
)
488 self
._write
('LSET %s %s %s\r\n%s\r\n' % (
489 name
, index
, len(value
), value
491 except UnicodeEncodeError, e
:
492 raise InvalidData("Error encoding unicode value for element %s in list '%s': %s." % (index
, name
, e
))
493 return self
.get_response()
495 def lrem(self
, name
, value
, num
=0):
500 >>> r.push('l', 'aaa')
502 >>> r.push('l', 'bbb')
504 >>> r.push('l', 'aaa')
506 >>> r.lrem('l', 'aaa')
508 >>> r.lrange('l', 0, 10)
510 >>> r.push('l', 'aaa')
512 >>> r.push('l', 'aaa')
514 >>> r.lrem('l', 'aaa', 1)
516 >>> r.lrem('l', 'aaa', 1)
518 >>> r.lrem('l', 'aaa', 1)
524 value
= value
if isinstance(value
, basestring
) else str(value
)
525 self
._write
('LREM %s %s %s\r\n%s\r\n' % (
526 name
, num
, len(value
), value
528 except UnicodeEncodeError, e
:
529 raise InvalidData("Error encoding unicode value for element %s in list '%s': %s." % (index
, name
, e
))
530 return self
.get_response()
532 def sort(self
, name
, by
=None, get
=None, start
=None, num
=None, desc
=False, alpha
=False):
537 >>> r.push('l', 'ccc')
539 >>> r.push('l', 'aaa')
541 >>> r.push('l', 'ddd')
543 >>> r.push('l', 'bbb')
545 >>> r.sort('l', alpha=True)
546 ['aaa', 'bbb', 'ccc', 'ddd']
549 >>> for i in range(1, 5):
550 ... res = r.push('l', 1.0 / i)
552 ['0.25', '0.333333333333', '0.5', '1.0']
553 >>> r.sort('l', desc=True)
554 ['1.0', '0.5', '0.333333333333', '0.25']
555 >>> r.sort('l', desc=True, start=2, num=1)
557 >>> r.set('weight_0.5', 10)
559 >>> r.sort('l', desc=True, by='weight_*')
560 ['0.5', '1.0', '0.333333333333', '0.25']
561 >>> for i in r.sort('l', desc=True):
562 ... res = r.set('test_%s' % i, 100 - float(i))
563 >>> r.sort('l', desc=True, get='test_*')
564 ['99.0', '99.5', '99.6666666667', '99.75']
565 >>> r.sort('l', desc=True, by='weight_*', get='test_*')
566 ['99.5', '99.0', '99.6666666667', '99.75']
567 >>> r.sort('l', desc=True, by='weight_*', get='missing_*')
568 [None, None, None, None]
571 stmt
= ['SORT', name
]
573 stmt
.append("BY %s" % by
)
575 stmt
.append("LIMIT %s %s" % (start
, num
))
578 elif isinstance(get
, basestring
):
579 stmt
.append("GET %s" % get
)
580 elif isinstance(get
, list) or isinstance(get
, tuple):
582 stmt
.append("GET %s" % g
)
584 raise RedisError("Invalid parameter 'get' for Redis sort")
590 self
._write
(' '.join(stmt
+ ["\r\n"]))
591 return self
.get_response()
593 def sadd(self
, name
, value
):
596 >>> res = r.delete('s')
604 # same considerations on unicode as in set() apply here
606 value
= value
if isinstance(value
, basestring
) else str(value
)
607 self
._write
('SADD %s %s\r\n%s\r\n' % (
608 name
, len(value
), value
610 except UnicodeEncodeError, e
:
611 raise InvalidData("Error encoding unicode value for element in set '%s': %s." % (name
, e
))
612 return self
.get_response()
614 def srem(self
, name
, value
):
619 >>> r.srem('s', 'aaa')
625 >>> r.sismember('s', 'b')
630 # same considerations on unicode as in set() apply here
632 value
= value
if isinstance(value
, basestring
) else str(value
)
633 self
._write
('SREM %s %s\r\n%s\r\n' % (
634 name
, len(value
), value
636 except UnicodeEncodeError, e
:
637 raise InvalidData("Error encoding unicode value for element in set '%s': %s." % (name
, e
))
638 return self
.get_response()
640 def sismember(self
, name
, value
):
645 >>> r.sismember('s', 'b')
649 >>> r.sismember('s', 'b')
651 >>> r.sismember('s', 'a')
656 # same considerations on unicode as in set() apply here
658 value
= value
if isinstance(value
, basestring
) else str(value
)
659 self
._write
('SISMEMBER %s %s\r\n%s\r\n' % (
660 name
, len(value
), value
662 except UnicodeEncodeError, e
:
663 raise InvalidData("Error encoding unicode value for element in set '%s': %s." % (name
, e
))
664 return self
.get_response()
666 def sinter(self
, *args
):
669 >>> res = r.delete('s1')
670 >>> res = r.delete('s2')
671 >>> res = r.delete('s3')
672 >>> r.sadd('s1', 'a')
674 >>> r.sadd('s2', 'a')
676 >>> r.sadd('s3', 'b')
680 ... except ResponseError, e:
682 wrong number of arguments
685 ... except ResponseError, e:
687 Operation against a key holding the wrong kind of value
688 >>> r.sinter('s1', 's2', 's3')
690 >>> r.sinter('s1', 's2')
695 self
._write
('SINTER %s\r\n' % ' '.join(args
))
696 return set(self
.get_response())
698 def sinterstore(self
, dest
, *args
):
701 >>> res = r.delete('s1')
702 >>> res = r.delete('s2')
703 >>> res = r.delete('s3')
704 >>> r.sadd('s1', 'a')
706 >>> r.sadd('s2', 'a')
708 >>> r.sadd('s3', 'b')
710 >>> r.sinterstore('s_s', 's1', 's2', 's3')
712 >>> r.sinterstore('s_s', 's1', 's2')
714 >>> r.smembers('s_s')
719 self
._write
('SINTERSTORE %s %s\r\n' % (dest
, ' '.join(args
)))
720 return self
.get_response()
722 def smembers(self
, name
):
733 ... except ResponseError, e:
735 Operation against a key holding the wrong kind of value
741 self
._write
('SMEMBERS %s\r\n' % name
)
742 return set(self
.get_response())
744 def select(self
, db
):
759 self
._write
('SELECT %s\r\n' % db
)
760 return self
.get_response()
762 def move(self
, name
, db
):
790 self
._write
('MOVE %s %s\r\n' % (name
, db
))
791 return self
.get_response()
793 def save(self
, background
=False):
799 ... resp = r.save(background=True)
800 ... except ResponseError, e:
801 ... assert str(e) == 'background save already in progress', str(e)
803 ... assert resp == 'OK'
808 self
._write
('BGSAVE\r\n')
810 self
._write
('SAVE\r\n')
811 return self
.get_response()
817 >>> t = int(time.time())
820 >>> r.lastsave() >= t
825 self
._write
('LASTSAVE\r\n')
826 return self
.get_response()
828 def flush(self
, all_dbs
=False):
833 >>> r.flush(all_dbs=True)
838 self
._write
('%s\r\n' % ('FLUSHALL' if all_dbs
else 'FLUSHDB'))
839 return self
.get_response()
845 >>> info and isinstance(info, dict)
847 >>> isinstance(info.get('connected_clients'), int)
852 self
._write
('INFO\r\n')
854 for l
in self
.get_response().split('\r\n'):
857 k
, v
= l
.split(':', 1)
858 info
[k
] = int(v
) if v
.isdigit() else v
861 def get_response(self
):
862 data
= self
._read
().strip()
865 raise ResponseError(data
[5:] if data
[:5] == '-ERR ' else data
[1:])
871 except (TypeError, ValueError):
872 raise InvalidResponse("Cannot convert multi-response header '%s' to integer" % data
)
875 result
.append(self
._get
_value
())
877 return self
._get
_value
(data
)
879 def _get_value(self
, data
=None):
880 data
= data
or self
._read
().strip()
884 c
, i
= data
[0], (int(data
[1:]) if data
.find('.') == -1 else float(data
[1:]))
886 raise InvalidResponse("Cannot convert data '%s' to integer" % data
)
890 raise InvalidResponse("Unkown response prefix for '%s'" % data
)
896 # we got the ending crlf
900 # the data has a trailing crlf embedded, let's restore it
901 buf
.append(self
._read
())
904 def disconnect(self
):
905 if isinstance(self
._sock
, socket
.socket
):
917 >>> isinstance(r._sock, socket.socket)
921 if isinstance(self
._sock
, socket
.socket
):
924 sock
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
925 sock
.connect((self
.host
, self
.port
))
926 except socket
.error
, e
:
927 raise ConnectionError("Error %s connecting to %s:%s. %s." % (e
.args
[0], self
.host
, self
.port
, e
.args
[1]))
930 self
._fp
= self
._sock
.makefile('r')
933 if __name__
== '__main__':