Mako模板中的UnicodeEncodeError

3 投票
2 回答
2222 浏览
提问于 2025-04-16 08:49

我有以下文件:

dummy.py

#!c:/Python27/python.exe -u

from mako import exceptions
from mako.template import Template

print "Content-type: text/html"
print

#VARIABLE = "WE" 
VARIABLE = "我们"
template = Template(filename='../template/dummy.html', output_encoding='utf8')
try:
    print template.render(VARIABLE=VARIABLE)
except:
    print exceptions.html_error_template().render()

dummy.html(以UTF-8格式保存)

hello world
哈罗世界
${VARIABLE}

我参考了这个网站的说明:http://www.makotemplates.org/docs/unicode.html

但是,我还是遇到了错误:

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

我是不是漏掉了什么?

2 个回答

2

是的,因为你试图把它转换成ASCII格式,这样是行不通的。你需要指定一下要使用什么样的输出编码:

Template(filename='../template/dummy.html', output_encoding='utf8')

另外,请不要使用空的异常捕获。要明确你希望捕获哪些异常。

6

在编程中,有时候我们会遇到一些问题,可能是因为代码写得不够清晰,或者是我们对某些概念理解得不够透彻。比如,有人可能在使用某个库的时候,遇到了错误提示,或者不知道该如何调用某个函数。这时候,查看一些技术论坛,比如StackOverflow,就能找到很多有用的信息和解决方案。

在这些论坛上,程序员们会分享他们的经验,讨论各种技术问题,甚至提供代码示例,帮助其他人理解如何解决类似的问题。通过这些交流,我们可以学习到很多实用的技巧和知识,让我们的编程能力不断提升。

总之,遇到问题时,不要害怕寻求帮助,利用好这些资源,可以让我们在编程的道路上走得更顺利。

template = Template(filename='../template/dummy.html', default_filters=['decode.utf8'], input_encoding='utf-8', output_encoding='utf-8')

撰写回答