【问题标题】:Google App engine template unicode decoding problemGoogle App引擎模板unicode解码问题
【发布时间】:2010-11-11 11:14:38
【问题描述】:

尝试在 Google App Engine 中呈现 Django 模板文件时

从 google.appengine.ext.webapp 导入模板

templatepath = os.path.join(os.path.dirname(file), 'template.html')
self.response.out.write (template.render( templatepath , template_values))

我遇到以下错误:

: “ascii”编解码器无法解码字节 0xe2 在位置 17692:序数不在 范围(128)
args = ('ascii', '个美丽的方法来找到内心的平静/ -->
', 17692, 17693, '序数不在范围内(128)')
编码 = 'ascii'
结束 = 17693
消息 = ''
object = '个美丽的方法来找到内心的平静/ -->
原因 = '序数不在范围内(128)'
开始 = 17692

似乎底层的django模板引擎已经假定了“ascii”编码,应该是“utf-8”。 谁知道可能是什么导致了麻烦以及如何解决? 谢谢。

【问题讨论】:

  • 你的 DEFAULT_CHARSET 值是多少? docs.djangoproject.com/en/dev/ref/request-response> 可能会有所帮助。

标签: python django google-app-engine unicode


【解决方案1】:

您是否在文本编辑器中检查了模板以 utf-8 编码?

【讨论】:

    【解决方案2】:

    您使用的是 Django 0.96 还是 Django 1.0?您可以通过查看您的 main.py 并查看它是否包含以下内容来检查:

    从 google.appengine.dist 导入 use_library use_library('django', '1.0')

    如果您使用的是 Django 1.0,则 FILE_CHARSET 和 DEFAULT_CHARSET 都应默认为“utf-8”。如果您的模板以不同的编码保存,只需将 FILE_CHARSET 设置为任何值。

    如果您使用的是 Django 0.96,您可能想尝试直接从磁盘读取模板,然后手动处理编码。

    例如,替换

    template.render( templatepath , template_values)

    Template(unicode(template_fh.read(), 'utf-8')).render(template_values)

    【讨论】:

      【解决方案3】:

      嗯,原来模板返回的渲染结果需要先解码:

      self.response.out.write (template.render(templatepath, template_values).decode('utf-8'))

      一个愚蠢的错误,但无论如何感谢大家的回答。 :)

      【讨论】:

        猜你喜欢
        • 2012-09-27
        • 2011-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-16
        • 2011-06-15
        • 2014-02-08
        • 1970-01-01
        相关资源
        最近更新 更多