13

makoを使用すると、このエラーが常に発生します。

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0' in position 6: ordinal not in range(128)

私はmakoに可能な限りユニコードを使用していると言いました:

    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オブジェクトをインスタンス化する方法でそれを処理する必要があります(そうでない場合、これらの引数は何に適していますか?)。忘れたことはありますか?

もう1つの質問:encoding_errors ='replace'のポイントは何ですか?

= EDIT =ユニコード文字列を1つだけ残しました。これは、トレースバックです。

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)
4

3 に答える 3

14

最後に、テンプレートをユニコードで保存しました。実際には(おそらく)utf-8ではなくutf-16です。ディスク上のサイズが2倍になり、makoが「CompileException(「エンコード'utf-8' bla blaのUnicodeデコード操作」)について不平を言い始めたので、すべての最初の行を次のように変更しました。

## -*- coding: utf-16 -*-

そして、すべての「.decode('utf-8')」を削除しました-定数文字列には、引き続き「u」が付いています

Pythonでの初期化は次のようになりました。

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で機能した理由を説明できません。

于 2010-07-27T11:15:35.257 に答える
2

グーガーのために:

mako.exceptions.CompileException: Unicode decode operation of encoding 'ascii' failed in fileテンプレートファイルにASCII以外の文字が含まれている場合、およびUnicode BOMがファイルに書き込まれていない場合、Makoは例外などを発生させます。BOMを手動で追加する必要があります(少なくとも私のテキストエディタでは、これは自動的には作成されません)。そのため、次のようになります。

$file test.htm
test.htm: HTML document, UTF-8 Unicode text

これになります:

$file test.htm
test.htm: HTML document, UTF-8 Unicode (with BOM) text
于 2013-05-21T11:24:26.773 に答える
0

これらの提案(受け入れられた回答を含む)はすべての場合、特にmakoテンプレートがコンテンツ(例:$ {value | n})をレンダリングし、値に非ASCII文字が含まれている場合には機能しません。

これは、デフォルトでmakoが生成されたコンパイル済みテンプレートの値をunicode(foo)でラップするためです。これにより、次の結果が得られます。

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0: ordinal not in range(128)

python2でmakoにunicodeを処理させる唯一の確実な方法は、次のようにデフォルト('unicode')ハンドラーを置き換えることです。

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)
于 2014-08-11T02:42:21.707 に答える