UnicodeDecodeError:'ascii'编解码器无法解码位置0中的字节0xe5:序号不在范围内(128)

我正在使用Flask和Google App Engine构build一个Web应用程序。 此Web应用程序中的其中一个页面通过YouTube API进行通话,以获取给定search字词的video。

当我尝试查询YoutubeVids.html时,出现以下错误。

这只有当我通过Jinja2模板传递一个特定的参数到页面时才会发生。

 file "/Users/xxxxx/App-Engine/src/templates/YoutubeVids.html", line 1, in top-level template code {% extends "master.html" %} UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128) INFO 2014-01-27 22:39:40,963 module.py:612] default: "GET /xxx/yyyy HTTP/1.1" 500 291 

弄清楚了。

我把我的python文件的开始以下内容

 import sys reload(sys) sys.setdefaultencoding("utf-8") 

从文档:Jinja2在内部使用Unicode,这意味着您必须将Unicode对象传递给渲染函数或只包含ASCII字符的字节串。

Python 2.x中的普通string是一个字节串。 为了使它unicode使用:

 byte_string = 'a Python string which contains non-ascii data like €äãü' unicode_string = byte_string.decode('utf-8') 

更多: http : //blog.notdot.net/2010/07/Getting-unicode-right-in-Python