问题
截至文章发布,python
中redis
的依赖已经升级到3.5.3
。而我是第一次使用python连接redis。业务需要我将一个dict
存入redis
,在连接到redis
后,我尝试直接存入字典类型。
报错。从这里开始解决问题。
redis.exceptions.DataError: Invalid input of type: 'dict'. Convert to a bytes, string, int or float first.
意思参数不符合规则,这里参数只接受a bytes, string, int or float
这几种类型。
过程
方案一
第一步当然是百度报错,几乎所有的方案都是减低版本,只需要将redis
依赖降低到2.10.6
就可以将参数设置为字典类型。
pip install redis==2.10.6
改了之后确实可以运行了。我去pypi
访问了redis
的主页,上面说(谷歌翻译,凑合看)
而且更严重的是,以后所有的新版本都不再兼容旧版。所以降低版本只能是权宜之计,掌握新版的方法才能从根本解决问题。
方案二
使用hset()方法
def hset(self, name, key=None, value=None, mapping=None):
"""
Set ``key`` to ``value`` within hash ``name``,
``mapping`` accepts a dict of key/value pairs that that will be
added to hash ``name``.
Returns the number of fields that were added.
"""
参数
- name:是Hash的名称
- key:是Hash下元素的key
- value:Hash下元素key对应的value
如果需要给hash设定过期时间,需要单独调用方法
如果需要获取hash
,不能使用get()
方法
import redis
pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
r = redis.Redis(connection_pool=pool)
test_list = [1, 2, 3, "123", [1, 2, 3, "123"]]
dict_list = {"test_list": [1, 2, 3, "123", [1, 2, 3, "123"]], "test_list2": [1, 2, 3]}
for dl in dict_list:
r.hset("dl_hash", dl, str(dict_list[dl]))
# 设置过期时间,单位秒
r.expire("dl_hash", 6000)
# 获取整个hash
print(r.hgetall("dl_hash"))
# 根据key获取单独的value
print(r.hget("dl_hash", "test_list"))
redis中存入结果
打印结果