在发生连接错误时,Python Redis中的UnicodeDecodeError

问题描述:

我正在编写一些单元测试以测试与Redis的连接。在某些时候,我希望连接失败,并且Python Redis提高RedisConnectionError在发生连接错误时,Python Redis中的UnicodeDecodeError

虽然底层套接字连接失败并确实会引发错误(WSACONNECTIONREFUSED),但文本消息使用我的语言环境设置:消息是法语的。

这似乎引起麻烦到Python Redis的,因为它明显地试图将错误回报给执行这段代码上层:

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()更改语言环境,但消息仍为法文。

你在那看到什么解决方案?

+0

我没有看到强制转换为Unicode的原因。如果格式字符串是Unicode但是参数是字节字符串('u“%s”%'\ x92''),我会期待这个错误。 – 2014-10-11 03:45:35

检查异常参数的类型。如果其中一个是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'