python redis存入字典序列化存儲(chǔ)教程
在python中通過redis hset存儲(chǔ)字典時(shí),必須主動(dòng)把字典通過json.dumps()序列化為字符串后再存儲(chǔ),
不然hget獲取后將無法通過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ǔ)教程就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法2. SpringBoot集成SSM、Dubbo、Redis、JSP的案例小結(jié)及思路講解3. python爬蟲利用代理池更換IP的方法步驟4. JavaScript forEach中return失效問題解決方案5. JS算法題解旋轉(zhuǎn)數(shù)組方法示例6. PHP設(shè)計(jì)模式之迭代器模式Iterator實(shí)例分析【對(duì)象行為型】7. VMware如何進(jìn)入BIOS方法8. python中pandas.read_csv()函數(shù)的深入講解9. Python語言規(guī)范之Pylint的詳細(xì)用法10. springboot用controller跳轉(zhuǎn)html頁面的實(shí)現(xiàn)
