首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在mako中处理unicode?

如何在mako中处理unicode?
EN

Stack Overflow用户
提问于 2010-07-26 17:19:18
回答 3查看 9.1K关注 0票数 13

我经常使用mako得到这个错误:

代码语言:javascript
复制
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0' in position 6: ordinal not in range(128)

我已经告诉mako我正在以任何可能的方式使用unicode:

代码语言:javascript
复制
    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)

我的所有模板文件都以:

代码语言:javascript
复制
## -*- coding: utf-8 -*-

而且,在它们内部,所有的常量字符串都以"u“为前缀。我知道self.stuff参数包含unicode字符串,但是我实例化mako对象的方式应该注意到它(否则这些参数有什么用呢?)。有什么我忘了做的事吗?

还有一个问题:编码错误=‘replace’的意义是什么?

=EDIT=我只留下了一个unicode字符串,这是回溯:

代码语言:javascript
复制
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)
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-07-27 19:15:35

最后,我用unicode保存了我的模板,实际上(我猜)是utf-16而不是utf-8。它们在磁盘上的大小翻了一番,mako开始抱怨“CompileException”(“编码'utf-8‘bla的Unicode解码操作”),所以我在下面的代码中更改了它们中的第一行:

代码语言:javascript
复制
## -*- coding: utf-16 -*-

并删除了所有".decode('utf-8')“-常量字符串仍然以"u”为前缀。

python中的初始化现在是:

代码语言:javascript
复制
mylookup = TemplateLookup(
    directories=['plugins/stl/templates'],
    input_encoding='utf-16',
    output_encoding='utf-16',
    encoding_errors='replace')

self.template = Template(self.getTemplate(), lookup=mylookup,
    module_directory=tempfile.gettempdir(),
    input_encoding='utf-16',
    output_encoding='utf-16',
    encoding_errors='replace')

它现在起作用了。看起来utf-8是一个错误的选择(或者我无法保存utf-8中的模板),但是我不能解释为什么它在eclipse/pydev中工作。

票数 14
EN

Stack Overflow用户

发布于 2013-05-21 19:24:27

为了谷歌员工:

当您的模板文件包含非ascii字符,并且Unicode BOM未写入文件时,Mako将引发异常mako.exceptions.CompileException: Unicode decode operation of encoding 'ascii' failed in file等。您需要手动添加BOM (这不是自动添加的,至少在我的文本编辑器中是这样的),以便:

代码语言:javascript
复制
$file test.htm
test.htm: HTML document, UTF-8 Unicode text

变成这样:

代码语言:javascript
复制
$file test.htm
test.htm: HTML document, UTF-8 Unicode (with BOM) text
票数 2
EN

Stack Overflow用户

发布于 2014-08-11 10:42:22

这些建议(包括接受的答案)在所有情况下都不起作用,特别是在mako模板呈现内容的情况下(例如,${value | n}),其中值包含非ascii字符。

这是因为在默认情况下,mako将unicode(foo)包装在生成的已编译模板中的任何值周围,这仍将导致:

代码语言:javascript
复制
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0: ordinal not in range(128)

让mako在python2中处理unicode的唯一可靠方法是替换默认的('unicode')处理程序,如下所示:

代码语言:javascript
复制
def handle_unicode(value):
    if isinstance(value, basestring):
        return unicode(value.decode('ascii', errors='ignore'))
    return unicode(value)


...    

lookup = TemplateLookup(
    directories=[self._root.template_path],
    imports=['from utils.view import handle_unicode'],
    default_filters=["handle_unicode"]
)

...

template = self._lookup.get_template(self.template())
rtn = template.render(request=self.request)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3333550

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档