这篇文章主要介绍了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)<em style="color:transparent">来源[email protected]搞@^&代*@码网</em>)
输出
{'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存入字典序列化存储教程的详细内容,更多请关注gaodaima搞代码网其它相关文章!