工作笔记——python如何向redis中存储hash

问题

截至文章发布,pythonredis的依赖已经升级到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中存入结果
在这里插入图片描述
打印结果
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值