发生连接错误时Python Redis中的UnicodeDecodeError
我正在编写一些单元测试来测试与Redis的连接。在某个时刻,我预计连接会失败,Python Redis会引发RedisConnectionError 但是,发生的情况是,底层套接字连接失败,并确实引发错误WSA connection Rejected,但文本消息使用我的区域设置:消息是法语的 这似乎给Python Redis带来了麻烦,因为它显然试图向执行这段代码的上层报告该错误:发生连接错误时Python Redis中的UnicodeDecodeError,python,unicode,redis,locale,redis-py,Python,Unicode,Redis,Locale,Redis Py,我正在编写一些单元测试来测试与Redis的连接。在某个时刻,我预计连接会失败,Python Redis会引发RedisConnectionError 但是,发生的情况是,底层套接字连接失败,并确实引发错误WSA connection Rejected,但文本消息使用我的区域设置:消息是法语的 这似乎给Python Redis带来了麻烦,因为它显然试图向执行这段代码的上层报告该错误: def _error_message(self, exception): # args for socke
def _error_message(self, exception):
# args for socket.error can either be (errno, "message")
# or just "message"
if len(exception.args) == 1:
return "Error connecting to %s:%s. %s." % \
(self.host, self.port, exception.args[0])
else:
return "Error %s connecting to %s:%s. %s." % \
(exception.args[0], self.host, self.port, exception.args[1])
这会导致UnicodeDecodeError,如下所示:
File "F:\environment\lib\site-packages\redis-2.8.1.a-py2.7.egg\redis\connection.py", line 312, in send_command
self.send_packed_command(self.pack_command(*args))
File "F:\environment\lib\site-packages\redis-2.8.1.a-py2.7.egg\redis\connection.py", line 294, in send_packed_command
self.connect()
File "F:\environment\lib\site-packages\redis-2.8.1.a-py2.7.egg\redis\connection.py", line 236, in connect
raise ConnectionError(self._error_message(e))
File "F:\environment\lib\site-packages\redis-2.8.1.a-py2.7.egg\redis\connection.py", line 261, in _error_message
(exception.args[0], self.host, self.port, exception.args[1])
UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 18: ordinal not in range(128)
事实上,我们可以看到实际的错误信息是:
'Aucune connexion n\x92a pu \xeatre \xe9tablie car l\x92ordinateur cible l\x92a express\xe9ment refus\xe9e'
这对我来说似乎很奇怪,因为我可能不是地球上唯一一个使用Python Redis的人,它是一个非英语语言环境。然而,我在互联网上找不到其他人面临同样的问题
在调用之前,我已经尝试使用setlocale更改区域设置,但消息仍然是法语
您看到了哪些解决方案?检查异常参数的类型。如果其中一个是Unicode,而另一个不是Unicode,则会发生错误:
>>> '%s %s' % ('\x92',u'\x92')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 0: ordinal not in range(128)
>>> '%s %s' % (u'\x92','\x92')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 0: ordinal not in range(128)
>>> '%s %s' % ('\x92','\x92') # Doesn't occur if both are byte strings
'\x92 \x92'
>>> '%s %s' % (u'\x92',u'\x92') # or both Unicode strings.
u'\x92 \x92'
我看不出强制使用Unicode的理由。如果格式字符串是Unicode,但参数是字节字符串u%s%'\x92',则可能会出现此错误。