简体   繁体   English

在Python应用程序中国际化子包

[英]Internationalizing subpackages in a Python application

I have an internationalized application written against Python 2.7. 我有一个针对Python 2.7编写的国际化应用程序。 In it I use a few packages I have written. 在其中,我使用了一些我编写的软件包。 I would like user-visible text in these packages to be translated. 我希望翻译这些软件包中的用户可见文本。

Given that the application installs _ into the __builtin__ namespace with translation.install , how do I get the individual packages to have their text translated with their particular translations which have their own domains? 假设应用程序通过translation.install_安装到__builtin__命名空间中,我如何获取各个软件包以将其文本翻译为具有各自域的特定翻译? Is it possible to merge two translations, for instance? 例如,是否可以合并两个翻译? Then I could just have the application merge the packages translation on import if I put it in a conventional place. 然后,如果我将其放在常规位置,则可以让应用程序在导入时合并软件包翻译。

Do I have to define _ and my other gettext helpers at the top of each subpackage? 我是否必须在每个子包的顶部定义_和其他gettext帮助器? If so, how can they pick up on the application's configured language while remaining loosely coupled? 如果是这样,他们如何在保持松散耦合的同时选择应用程序配置的语言?

This feels like it's more complicated than it should be, which leads me to believe I'm not understanding something. 感觉这比应该做的要复杂得多,这使我相信自己对某些事情不了解。

I would recommend not installing _ into builtins, but rather defining it inside your package's __init__ and explicitly importing it in the other modules. 我建议不要将_安装到内置函数中,而应在包的__init__定义它,然后将其显式导入其他模块中。

Eg mypackage/__init__.py : 例如mypackage/__init__.py

import gettext
translations = gettext.translation('mypackage')
_ = translations.ugettext

and then elsewhere 然后在其他地方

from mypackage import _

some_string = _("Something that will be translated")

I haven't actually used gettext in a long while, so take this example with a gain of salt (although it was based on the recommendation in gettext's documentation ). 我已经有很长时间没有实际使用gettext了,所以以这个例子为例(尽管它是基于gettext文档中建议 )。

I've been mostly working with Zope-based web applications that cannot do the translation during module import -- we need to delay the actual translation until request rendering time, so we know the user's preferred language. 我主要使用基于Zope的Web应用程序,这些模块在模块导入期间无法进行翻译-我们需要将实际翻译延迟到请求呈现时间,以便我们知道用户的首选语言。 We use zope.i18nmessageid's MessageFactory to mark strings for translation in a very similar way: 我们使用zope.i18nmessageid的MessageFactory以非常相似的方式标记要翻译的字符串:

# mypackage/__init__.py
from zope.i18nmessageid import MessageFactory
_ = MessageFactory("mypackage")

# mypackage/somemodule.py
from mypackage import _
some_string = _("Something that will be translated later")
# e.g. with print zope.i18n.translate(some_string, request)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM