14-简便用法
5.3.3 简便用法
1. HMSET/HGETALL
HMSET
支持将字典作为参数存储,同时 HGETALL
的返回值也是一个字典,搭配使用十分方便:
r.hmset('dict', {'name': 'Bob'})
people = r.hgetall('dict')
print people # {'name': 'Bob'}
2.事务和管道
redis-py的事务使用方式如下:
pipe = r.pipeline()
pipe.set('foo', 'bar')
pipe.get('foo')
result = pipe.execute()
print result # [True, 'bar']
管道的使用方式和事务相同,只不过需要在创建时加上参数 transaction=False
:
pipe = r.pipeline(transaction=False)
事务和管道还支持链式调用:
result = r.pipeline().set('foo', 'bar').get('foo').execute()
# [True, 'bar']