1

我正在编写一些单元测试来测试与 Redis 的连接。在某些时候,我预计连接会失败并且 Python Redis 会引发RedisConnectionError.

但是会发生什么是底层套接字连接失败并且确实引发了错误(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()在通话前使用更改语言环境,但消息仍然是法语。

您在那里看到了哪些解决方案?

4

1 回答 1

0

Check the types of your exception arguments. If one of them is Unicode and one is not that error will occur:

>>> '%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'
于 2014-10-11T03:50:15.663 回答