欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

Python操作Redis的5种数据类型

发布时间:2024/1/17 python 37 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Python操作Redis的5种数据类型 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

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

 

 

  

转载于:https://www.cnblogs.com/logicalsky/p/5946647.html

总结

以上是生活随笔为你收集整理的Python操作Redis的5种数据类型的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。