当前位置:嗨网首页>书籍在线阅读

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']