我经常使用 mako 得到这个错误:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0' in position 6: ordinal not in range(128)
我已经告诉 mako 我正在以任何可能的方式使用 unicode:
mylookup = TemplateLookup(
directories=['plugins/stl/templates'],
input_encoding='utf-8',
output_encoding='utf-8',
default_filters=['decode.utf8'],
encoding_errors='replace')
self.template = Template(self.getTemplate(), lookup=mylookup,
module_directory=tempfile.gettempdir(),
input_encoding='utf-8',
output_encoding='utf-8',
default_filters=['decode.utf8'],
encoding_errors='replace')
html = self.template.render_unicode(data=self.stuff)
我所有的模板文件都以:
## -*- coding: utf-8 -*-
并且,在它们内部,所有常数字符串都以“u”为前缀。我知道 self.stuff 参数包含 unicode 字符串,但我实例化 mako 对象的方式应该处理它(否则这些参数有什么用?)。有什么我忘了做的吗?
还有一个问题: encoding_errors='replace' 有什么意义?
=EDIT= 我只留下了一个 unicode 字符串,这是回溯:
Traceback (most recent call last):
File "C:\My Dropbox\src\flucso\src\plugins\stl\main.py", line 240, in updateView
flags=self.makoflags)
File "C:\Python26\lib\site-packages\mako-0.3.4-py2.6.egg\mako\template.py", line 198, in render_unicode
as_unicode=True)
File "C:\Python26\lib\site-packages\mako-0.3.4-py2.6.egg\mako\runtime.py", line 403, in _render
_render_context(template, callable_, context, *args, **_kwargs_for_callable(callable_, data))
File "C:\Python26\lib\site-packages\mako-0.3.4-py2.6.egg\mako\runtime.py", line 434, in _render_context
_exec_template(inherit, lclcontext, args=args, kwargs=kwargs)
File "C:\Python26\lib\site-packages\mako-0.3.4-py2.6.egg\mako\runtime.py", line 457, in _exec_template
callable_(context, *args, **kwargs)
File "memory:0x41317f0", line 89, in render_body
File "C:\Python26\lib\site-packages\mako-0.3.4-py2.6.egg\mako\runtime.py", line 278, in <lambda>
return lambda *args, **kwargs:callable_(self.context, *args, **kwargs)
File "FriendFeed_mako", line 49, in render_inlist_entry
File "C:\Python26\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u263c' in position 8: ordinal not in range(128)