2014-01-27 109 views
34

我正在使用Flask和Google App Engine構建Web應用程序。此Web應用程序中的其中一個頁面通過YouTube API調用以獲取給定搜索字詞的視頻。UnicodeDecodeError:'ascii'編解碼器無法解碼位置0中的字節0xe5:序號不在範圍內(128)

當我嘗試查詢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 

回答

84

想通了。

我把下面我Python文件開始

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

或者您可以使用:從__future__開始導入unicode_literals。 – voscausa

+0

不...不......你爲什麼要那樣做? –

+0

@Matt Nordhoff:爲什麼不呢?我一直這樣做(以上給出了一個錯誤)。 – orome

10

從文檔:Jinja2在內部使用Unicode,這意味着您必須將Unicode對象傳遞給渲染函數或只包含ASCII字符的字節串。

Python 2.x中的普通字符串是一個字節串。爲了使它的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

+2

此外,[務實的Unicode(http://nedbatchelder.com/text/unipain.html)由斯內德爾德,[瓶的Unicode的文檔](http://flask.pocoo.org/docs/dev/unicode/)和[Jinja的Unicode文檔](http://jinja.pocoo.org/docs/dev/api/#unicode)。 –

相關問題