您的位置:首页 > 数据库 > Redis

Redis 中文入库成功,读取数据写入文件乱码问题

2014-06-10 15:36 387 查看
最近需要用到redis ,但是在编码这个问题上,纠结了很久。

需求 :每天一个进程将中文文件入库到redis中(不定时更新) ,另外几个进程读取redis中的信息 ,并处理数据结果。使用的redis模块 :入库正常,读取数据成功,以GBK编码写入文件出现异常。 通过以下参数连接 redis :

client = redis.StrictRedis(host='localhost', port=6379, db=0, password="***") 从stackoverflow上了解到 :最好传入一个str类型的value给redis,而不是unicode,否则,redis会直接使用set命令,将你的value设置为utf-8的格式,当你使用get方法获取数据的时候,redis本身并不关心你value的数据的类型,而给你返回一个str类型的value。因此,你存储的时候value的类型是关键所在
,主要体现在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 连接数据库时 :

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)


通过设置上述参数,解决了编码问题。

如果有人有更好的解释和解决方案,求分享!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: