【问题标题】:UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)UnicodeDecodeError:“ascii”编解码器无法解码位置 0 的字节 0xe5:序数不在范围内(128)
【发布时间】:2014-02-19 01:16:14
【问题描述】:

我正在使用 Flask 和 Google App Engine 构建一个网络应用程序。此 Web 应用程序中的一个页面通过 YouTube API 进行调用,以获取给定搜索词的视频。

当我尝试查询 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

【问题讨论】:

    标签: api google-app-engine youtube flask


    【解决方案1】:

    想通了。

    我将以下内容放在我的 python 文件的开头

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

    【讨论】:

    • 或者你可以使用:from future import unicode_literals at the start.
    • 不……不要……你为什么要那样做?
    • @Matt Nordhoff:为什么不呢?我一直在这样做(上面给出了一个错误)。
    • @raxacoricofallapatorius:见Dangers of sys.setdefaultencoding('utf-8')
    • @idbrii:是的。似乎没有办法取胜(也许 Python 3 除外?)!
    【解决方案2】:

    来自文档: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

    【讨论】:

    猜你喜欢
    • 2011-05-13
    • 2018-07-26
    • 2020-11-06
    • 2014-08-12
    • 2013-09-20
    • 2016-07-05
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多