[Solved] UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xe9 in position 0: ordinal not in range solution

Directory

  • 1. The question shows
  • 2. Problem Analysis
  • 3. Solution

1. As shown in the question

when transferring data
The problem occurs as follows:

 File "./audioadmin/common.py", line 331, in send_alarm
    .format(content, project_name, result))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 0: ordinal not in range(128)

Screenshot below:

2. Problem Analysis

python2.7 version: (version 2 used in the project):
Python’s encoding conversion will use unicode as an intermediate transcoding (unicode only has a length of 128)
The encoding process is to first convert its Ascii encoded characters (the default encoding method) to unicode
Through the above log, you can know that the transcoding cannot be performed. If it exceeds the range, this error log will be reported.
When encoding itself, sys.defaultencoding defaults to Ascii, and the incoming encoding is utf-8. The format is different, and an error is naturally reported.

This kind of problem is already compatible with python3 version and above
Test for python3 compatibility issues:

import sys


sys.getdefaultencoding() # output utf-8, while in python2.7 it will output Ascii

3. Solutions

Introduce at the beginning of the project:

import sys
defaultencoding = 'utf-8'
if sys.getdefaultencoding() != defaultencoding:
    reload(sys)
    sys.setdefaultencoding(defaultencoding)