python redis存入字典序列化存儲(chǔ)教程
在python中通過(guò)redis hset存儲(chǔ)字典時(shí),必須主動(dòng)把字典通過(guò)json.dumps()序列化為字符串后再存儲(chǔ),
不然hget獲取后將無(wú)法通過(guò)json.loads()反序列化為字典
序列化存儲(chǔ)
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’}
補(bǔ)充知識(shí):python redis 存string 取 string
看代碼吧~
DB_REDIS = { ’host’: localhost, ’port’: 6379, ’password’: ’pwd&&1’, ’db’: 1, ’decode_responses’: True}
python3使用時(shí),給客戶端配置’decode_responses’: True
就能保證存取的都是string,而不是想存string,結(jié)果卻是bytes!!!
以上這篇python redis存入字典序列化存儲(chǔ)教程就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼2. PHP橋接模式Bridge Pattern的優(yōu)點(diǎn)與實(shí)現(xiàn)過(guò)程3. asp.net core項(xiàng)目授權(quán)流程詳解4. html中的form不提交(排除)某些input 原創(chuàng)5. CSS3中Transition屬性詳解以及示例分享6. bootstrap select2 動(dòng)態(tài)從后臺(tái)Ajax動(dòng)態(tài)獲取數(shù)據(jù)的代碼7. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式8. 開(kāi)發(fā)效率翻倍的Web API使用技巧9. jsp文件下載功能實(shí)現(xiàn)代碼10. ASP常用日期格式化函數(shù) FormatDate()
