码迷,mamicode.com
首页 > 编程语言 > 详细

Python操作Redis的5种数据类型

时间:2016-10-11 11:24:24      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:

1.连接redis(两种方式)

  •  
    1  # decode_responses=True: 解决获取的值类型是bytes字节问题
    2  r = redis.Redis(host=localhost, port=6379, db=0, decode_responses=True)
  •   

    1  pool = redis.ConnectionPool(host=localhost, port=6379, db=0, decode_responses=True)
    2  r = redis.Redis(connection_pool=pool)

2.字符串类型 String

1  # ex过期时间 单位秒S
2  r.set(name, Jack, ex=20)
3  rst = r.get(name)
4  print(rst)
5  
6  
7  结果: "Jack"

3.列表类型 list    

 1  r.lpush(object, one)
 2  r.lpush(object, two)
 3  r.lpush(object, three)
 4  r.lpush(object, four)
 5  r.lpush(object, five)
 6  r.lpush(object, six)
 7  ret = r.lrange(object, 0, 5)
 8  print(ret[::-1], len(ret))
 9    
10   
11  结果: [one, two, three, four, five, six]  6

4.哈希类型  hash

1  r.hset(user:info, name, Jack)
2  r.hset(user:info, age, 20)
3  r.hset(user:info, phone, 18712909999)
4  r.hset(user:info, email, 123@gmail.com)
5  rst = r.hgetall(user:info)
6  print(rst)
7 
8 
9  结果: {age: 20, email: 123@gmail.com, name: Jack, phone: 18712909999}

5.集合类型  set

1  r.sadd(set, one)
2  r.sadd(set, two)
3  r.sadd(set, three)
4  res = r.smembers(set)
5  print(res)
6 
7 
8  结果: {two, one, three}

6.有序集合类型 sorted set 

 1  r.zadd(mark, one, 1)
 2  r.zadd(mark, two, 2)
 3  r.zadd(mark, three, 3)
 4  r.zadd(mark, four, 4)
 5  r.zadd(mark, five, 5)
 6  result = r.zrange(mark, 0, 10)
 7  print(result)
 8 
 9 
10  结果: [one, two, three, four, five]

 

 

  

Python操作Redis的5种数据类型

标签:

原文地址:http://www.cnblogs.com/logicalsky/p/5946647.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!