3.6 Python操作Redis

Redis也是一种非关系型数据库,Redis服务器通常被称为数据结构服务器,因为值(value)可以是 字符串(String), 哈希(Map), 列表(list), 集合(sets) 和 有序集合(sorted sets)等类型 。

使用Redis需要对数据结构有个初步认识,比如:

  • String: 字符串

  • Hash: 散列

  • List: 列表

  • Set: 集合

  • Sorted Set: 有序集合

pymysql一样,redis库也只提供了与原始redis一致的SQL命令来操作数据库,所以要使用好redis数据库,还需要了解如何直接操作redis数据库。

Redis的基本教程与Python操作教程可以在如下地址找到。

基于此教程做了一下最简单的实验,代码与解释如下。

from redis import StrictRedis,ConnectionPool

# 1.连接数据库
# 连接redis本地数据库,选择db1
redis0 = StrictRedis(host='localhost',port=6379,db=1)

# 使用ConnectionPool方法连接数据库,选择数据库db0
url = 'redis://:@localhost:6379/0'
pool = ConnectionPool.from_url(url)
redis1 = StrictRedis(connection_pool=pool)

# 2. 操作字符串 String
redis0.set('name_test_string','MarcoMei')
# 读取字符串key值
print(redis0.get('name_test_string'))

# 3. 操作列表List
# 尾部插入列表数据
redis0.rpush('score_test_list',1,2,3)
# 头部插入列表数据
redis0.lpush('score_test_list',4,5,6)

# 4. 操作集合Set
# 向名为tag_test_set的集合中添加多个内容:Book, Tea, Coffee
redis0.sadd('tag_test_set','Book','Tea','Coffee')
# 查看集合tag_test_set的内容
print(redis0.smembers('tag_test_set'))

# 5. 操作有序集合Sorted Set
redis0.zadd('grade_test_sorted',100,'Marco',99,'Kevin')

# 6. 操作哈希Hash:即是一个Hash表的键值对数据结构
# 添加一对一关系数据结构, cake: 5
redis0.hset('price_test_hash1', 'cake', 5)
redis0.hget('price_test_hash1','cake')
# 添加多个键值对的数据结构,
redis0.hmset('price_test_hash2', {'cake': 5,'price':20,'weight':'big','name':'for_marco'} )

用例

应用库:Requests发起请求获取响应数据, PyQuery解析响应数据获得想要的数据, pymongo保存数据到MongoDB数据库

Last updated