近期須要用到redis ,可是在編碼這個(gè)問題上,糾結(jié)了非常久。
? ? ? ?需求 :每天一個(gè)進(jìn)程將中文文件入庫到redis中(不定時(shí)更新) ,另外幾個(gè)進(jìn)程讀取redis中的信息 ,并處理數(shù)據(jù)結(jié)果。使用的redis模塊 :入庫正常,讀取數(shù)據(jù)成功,以GBK編碼寫入文件出現(xiàn)異常。 ?通過下面參數(shù)連接 redis :
? ? ? ?client ?= redis.StrictRedis(host='localhost', port=6379, db=0, password="***") 從stackoverflow上了解到 :最好傳入一個(gè)str類型的value給redis,而不是unicode,否則,redis會直接使用set命令,將你的value設(shè)置為utf-8的格式,當(dāng)你使用get方法獲取數(shù)據(jù)的時(shí)候,redis本身并不關(guān)心你value的數(shù)據(jù)的類型,而給你返回一個(gè)str類型的value。因此,你存儲的時(shí)候value的類型是關(guān)鍵所在 ,主要體如今redis-py的源代碼中 :
""" Encode the value so that it's identical to what we'll read off the connection """ if self.decode_responses and isinstance(value, bytes): value = value.decode(self.encoding, self.encoding_errors) elif not self.decode_responses and isinstance(value, unicode): value = value.encode(self.encoding, self.encoding_errors) return value
?? 解決方法 : 在使用redis API 連接數(shù)據(jù)庫時(shí) :
class redis.StrictRedis(host='localhost', port=6379, db=0, password=None, socket_timeout=None,connection_pool=None, charset='GBK', errors='strict', decode_responses=True, unix_socket_path=None)
通過設(shè)置上述參數(shù),攻克了編碼問題。
假設(shè)有人有更好的解釋和解決方式,求分享!
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
