时间:2021-04-25 10:11:24 | 栏目:Python代码 | 点击:次
在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!!!