这篇文章主要讲解了python redis存入字典序列化存储的方法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。
在python中通过redis hset存储字典时,必须主动把字典通过json.dumps()序列化为字符串后再存储,
不然hget获取后将无法通过json.loads()反序列化为字典
序列化存储
r = redis_conn()
r.hset('wait_task', 'one', json.dumps({'project': 'india', 'total_size': '15.8 MB'}))
r.hset('wait_task', 'two', json.dumps({'project': 'india', 'total_size': '15.8 MB'}))
r.hset('wait_task', 'three', json.dumps({'project': 'india', 'total_size': '15.8 MB'}))
反序列化读取
for k in r.hkeys('wait_task'):
d = r.hget('wait_task', k)
print(json.loads(d))
输出
{'project': 'india', 'total_size': '15.8 MB'}
{'project': 'india', 'total_size': '15.8 MB'}
{'project': 'india', 'total_size': '15.8 MB'}
补充知识:python redis 存string 取 string
看代码吧~
DB_REDIS = {
'host': localhost,
'port': 6379,
'password': 'pwd&&1',
'db': 1,
'decode_responses': True
}
python3使用时,给客户端配置'decode_responses': True
就能保证存取的都是string,而不是想存string,结果却是bytes!!!
看完上述内容,是不是对python redis存入字典序列化存储的方法有进一步的了解,如果还想学习更多内容,欢迎关注天达云行业资讯频道。