django 中文报错

在Django视图函数中常常出现相似于'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)的错误。python

在解决错误以前,首先要了解unicode和utf-8的区别。函数

unicode指的是万国码,是一种“字码表”。而utf-8是这种字码表储存的编码方法。unicode不必定要由utf-8这种方式编成bytecode储存,也能够使用utf-16,utf-7等其余方式。目前大多都以utf-8的方式来变成bytecode。编码

其次,python中字符串类型分为byte string 和 unicode string两种。spa

若是在python文件中指定编码方式为utf-8(#coding=utf-8),那么全部带中文的字符串都会被认为是utf-8编码的byte string(例如:mystr="你好"),可是在函数中所产生的字符串则被认为是unicode stringcode

问题就出在这边,unicode string 和 byte string 是不能够混合使用的,一旦混合使用了,就会产生这样的错误。例如:utf-8

self.response.out.write("你好"+self.request.get("argu"))ci

其中,"你好"被认为是byte string,而self.request.get("argu")的返回值被认为是unicode string。因为预设的解码器是ascii,因此就不能识别中文byte string。而后就报错了。unicode

如下有两个解决方法:字符串

1.将字符串全都转成byte string。get

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")

相关文章
相关标签/搜索