Errors similar to ‘ascii’ codec ca n’t decode byte 0xef in position 0: ordinal not in range (128) often occur in Django view functions.
Before solving the error, we must first understand the difference between unicode and utf-8.
Unicode refers to the universal code, which is a kind of "code table". UTF-8 is the encoding method stored in this code table. Unicode does not have to be compiled into bytecode storage by utf-8, and other methods such as utf-16 and utf-7 can also be used. At present, most of them are turned into bytecode by utf-8.
Secondly, the string types in Python are divided into two types: byte string and unicode string.
If the encoding method is specified as utf-8 (# coding = utf-8) in the python file, then all strings with Chinese characters will be considered as utf-8 encoded byte strings (for example: mystr = "hello"), But the string generated in the function is considered a unicode string.
The problem lies here. Unicode string and byte string cannot be mixed. Once mixed, this error will occur. E.g:
self.response.out.write ("Hello" + self.request.get ("argu"))
Among them, "Hello" is regarded as a byte string, and the return value of self.request.get ("argu") is regarded as a unicode string. Since the preset decoder is ascii, it cannot recognize the Chinese byte string. Then I got an error.
There are two solutions:
1. Convert all character strings to byte string.
self.response.out.write ("Hello" + self.request.get ("argu"). encode ("utf-8"))
2. Convert all strings into unicode strings.
self.response.out.write (u "hello" + self.request.get ("argu"))
Convert byte string to unicode string can be converted to unicode (unicodestring, "utf-8")
'ascii' codec can't decode byte 0xef in position 0: ordinal not in range (128)-quote