通过默认方式与 Redis 建立连接:
>>> conn = redis.Redis()
基本的字符串操作:
True >>> conn.get('key-str') 'Hello World!'
尝试获取一个不存在的 key 会返回 None(控制台不会打印出来)
>>> conn.get('key-none')
Redis 的加/减操作:
如果一个变量的值可以被解析成10进制数或浮点数,则可以对它使用 INCR* 和 DECR* 操作。
True >>> conn.incr('fst-digit') 1 >>> conn.incr('fst-digit', 10) 11 >>> conn.decr('fst-digit') 10 >>> conn.decr('fst-digit', 5) 5 >>> conn.set('digit-str', '1') True >>> conn.incr('digit-str') 2
如果尝试加/减一个不存在的变量,Redis 会将其值当做 0 处理:
>>> conn.incr('digit-none') 1
如果一个变量的值不能被解析为数字,你将会收到异常:
True >>> conn.incr('str') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/site-packages/redis/client.py", line 651, in incr return self.execute_command('INCRBY', name, amount) File "/usr/local/lib/python2.7/site-packages/redis/client.py", line 394, in execute_command return self.parse_response(connection, command_name, **options) File "/usr/local/lib/python2.7/site-packages/redis/client.py", line 404, in parse_response response = connection.read_response() File "/usr/local/lib/python2.7/site-packages/redis/connection.py", line 316, in read_response raise response redis.exceptions.ResponseError: ERR value is not an integer or out of range
Redis 也支持多种类似于 Python 中的字符串操作方法,以下是一些简单的例子:
字符串的 append, 类型于 Python 中的“+”操作
6L >>> conn.append('string-key', 'world!') 12L
截取子字符串:
'lo wo'
从指定偏移位置开始写入新的子字符串
12 >>> conn.setrange('new-string-key', 6, 'W') 12 >>> conn.get('new-string-key') 'Hello World!' >>> conn.setrange('new-string-key', 11, ', how are you?') 25 >>> conn.get('new-string-key') 'Hello World, how are you?'
字节串操作:
0 >>> conn.setbit('another-key', 7, 1) 0 >>> conn.get('another-key') '!'