在Django視圖函數中經常出現類似於'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)的錯誤。
在解決錯誤之前,首先要了解unicode和utf-8的區別。
unicode指的是萬國碼,是一種“字碼表”。而utf-8是這種字碼表儲存的編碼方法。unicode不一定要由utf-8這種方式編成bytecode儲存,也可以使用utf-16,utf-7等其他方式。目前大多都以utf-8的方式來變成bytecode。
其次,Python中字符串類型分為byte string 和 unicode string兩種。
如果在python文件中指定編碼方式為utf-8(#coding=utf-8),那么所有帶中文的字符串都會被認為是utf-8編碼的byte string(例如:mystr="你好"),但是在函數中所產生的字符串則被認為是unicode string。
問題就出在這邊,unicode string 和 byte string 是不可以混合使用的,一旦混合使用了,就會產生這樣的錯誤。例如:
self.response.out.write("你好"+self.request.get("argu"))
其中,"你好"被認為是byte string,而self.request.get("argu")的返回值被認為是unicode string。由於預設的解碼器是ascii,所以就不能識別中文byte string。然后就報錯了。
以下有兩個解決方法:
1.將字符串全都轉成byte string。
self.response.out.write("你好"+self.request.get("argu").encode("utf-8"))
2.將字符串全都轉成unicode string。
self.response.out.write(u"你好"+self.request.get("argu"))
byte string轉換成unicode string可以這樣轉unicode(unicodestring, "utf-8")