使用 gettext 翻译 Tornado 模板时出错

Error translating Tornado template with gettext

我的网站 运行 位于 Tornado 及其模板引擎之上,我想将其国际化,所以我考虑使用 gettext 来帮助我。

由于我的站点已经是葡萄牙语,所以我的 message.po(模板)文件也包含所有葡萄牙语的 msgid(示例):

#: base.html:30 base.html:51
msgid   "Início"
msgstr  ""

它是用 xgettext 生成的:

xgettext -i *.html -L Python --from-code UTF-8

后来我用Poedit生成翻译文件en_US.po,后来编译成en_US.mo。 存放在我的翻译文件夹中:

translation/en_US/LC_MESSAGES/site.mo 

到目前为止,还不错。

我创建了一个非常简单的 RequestHandler,它可以呈现和 return 翻译后的网站。

import os
import logging
from tornado.web import RequestHandler
import tornado.locale as locale

LOG = logging.getLogger(__name__)

class SiteHandler(RequestHandler):

    def initialize(self):
        locale.load_gettext_translations(os.path.join(os.path.dirname(__file__), '../translations'), "site")

    def get(self, page):
        LOG.debug("PAGE REQUESTED: %s", page)
        self.render("site/%s.html" %page)

据我所知应该可以完美运行,但不知何故我遇到了一些问题:

1 - 我如何告诉 Tornado 我的模板有葡萄牙语文本,这样它就不会去寻找我没有的 pt 语言环境?

2 - 当请求具有 en_US 语言环境的站点时,它加载正常,但是当 Tornado 将要翻译时,它抛出一个编码异常。

TypeError: not all arguments converted during string formatting
ERROR:views.site:Could not load template
Traceback (most recent call last):
  File "/Users/ademarizu/Dev/git/new_plugin/site/src/main/py/views/site.py", line 20, in get
    self.render("site/%s.html" %page)
  File "/Users/ademarizu/Dev/virtualEnvs/execute/lib/python2.7/site-packages/tornado/web.py", line 664, in render
    html = self.render_string(template_name, **kwargs)
  File "/Users/ademarizu/Dev/virtualEnvs/execute/lib/python2.7/site-packages/tornado/web.py", line 771, in render_string
    return t.generate(**namespace)
  File "/Users/ademarizu/Dev/virtualEnvs/execute/lib/python2.7/site-packages/tornado/template.py", line 278, in generate
    return execute()
  File "site/home_html.generated.py", line 11, in _tt_execute
    _tt_tmp = _("Início")  # site/base.html:30
  File "/Users/ademarizu/Dev/virtualEnvs/execute/lib/python2.7/site-packages/tornado/locale.py", line 446, in translate
    return self.gettext(message)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/gettext.py", line 406, in ugettext
    return self._fallback.ugettext(message)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/gettext.py", line 407, in ugettext
    return unicode(message)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2: ordinal not in range(128)

有什么帮助吗?

啊,我是 运行 python 2.7 顺便说一句!

1 - How do I tell Tornado that my template has its text in Portuguese so it won't go looking for a pt locale which I don't have?

这就是 set_default_locale 方法的用途。在启动时调用 tornado.locale.set_default_locale('pt')(或 pt_BR 等)一次,告诉龙卷风您的模板源是葡萄牙语。

2 - When asking for the site with en_US locale, it loads ok but when Tornado is going to translate, it throws an encoding exception.

记住在Python2中,包含非ascii字符的字符串需要标记为unicode。使用 _(u"Início").

而不是 _("Início")