Oslo系列之oslo.i18n-上

千万人的失败,都有是失败在做事不彻底,往往做到离成功只差一步就终止不做了。

一般地,一个大型的项目,特别是一个跨国平台,都需要进行国际化支持。OpenStack作为一个开源的云平台方案,同样需要支持国际化。因此,OpenStack社区开发了oslo.i18n组件支持OpenStack项目的国际化。本文便简单的介绍了OpenStack支持国际化的实现与使用。

oslo.i18n的实现

OpenStack项目支持国际化的实现非常简单,在oslo.i18n中主要使用TranslatorFactory类实现国际化支持。该类中提供了primary()方法进行国际化翻译,而该类则实际调用了_make_translation_func(domain)实现具体的操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
def _make_translation_func(self, domain=None):
"""Return a translation function ready for use with messages.
The returned function takes a single value, the unicode string
to be translated. The return type varies depending on whether
lazy translation is being done. When lazy translation is
enabled, :class:`Message` objects are returned instead of
regular :class:`unicode` strings.
The domain argument can be specified to override the default
from the factory, but the localedir from the factory is always
used because we assume the log-level translation catalogs are
installed in the same directory as the main application
catalog.
"""
if domain is None:
domain = self.domain
t = gettext.translation(domain,
localedir=self.localedir,
fallback=True)
# Use the appropriate method of the translation object based
# on the python version.
m = t.gettext if six.PY3 else t.ugettext

def f(msg):
"""oslo_i18n.gettextutils translation function."""
if _lazy.USE_LAZY:
return _message.Message(msg, domain=domain)
return m(msg)
return f

在该方法中定义了两种实现国际化的方式:第一种方式是直接使用gettext模块生成一个翻译函数,输出国际化结果;而另一种方式可以理解为一种懒加载模式,如果你直接在代码中导入_,而不是通过gettextutils.install()方式导入,这种懒加载模式将会很有用。该模式返回一个oslo.i18n自己定义的Message对象缓存待翻译的unicode编码的信息,在实例化时通过调用Message类的静态方法_translate_msgid(msgid, domain)获取对应的国际化信息。

oslo.i18n的使用

国际化支持在OpenStack各项目中使用频繁,oslo.i18n为了使用更加的方便,定义了_表示一个TranslatorFactory对象的primary()方法,因此在使用国际化之前,首先需要导入_;另外,在为日志支持国际化时也特意定义了_LI、_LW、_LE、_LC等不同级别的国际化支持方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import oslo_i18n

DOMAIN = 'nova'

_translators = oslo_i18n.TranslatorFactory(domain=DOMAIN)

# The primary translation function using the well-known name "_"
_ = _translators.primary

# Translators for log levels.
#
# The abbreviated names are meant to reflect the usual use of a short
# name like '_'. The "L" is for "log" and the other letter comes from
# the level.
_LI = _translators.log_info
_LW = _translators.log_warning
_LE = _translators.log_error
_LC = _translators.log_critical

在使用时只需要导入这些方法的别名即可使用这些方法直接实现信息国际化的支持。

1
2
3
4
5
6
7
8
from nova.i18n import _, _LE

def _log_exception(self):
# kwargs doesn't match a variable in the message
# log the issue and the kwargs
LOG.exception(_LE('Exception in string format operation'))
for name, value in self.kwargs.items():
LOG.error("%s: %s" % (name, value)) # noqa

如上面的一段代码中,Nova组件使用_LE方法对一条异常信息进行了国际化打印的支持。

原文链接:https://blog.csdn.net/Bill_Xiang_/article/details/78570404

-------------本文结束 感谢您的阅读-------------
作者Magiceses
有问题请 留言 或者私信我的 微博
满分是10分的话,这篇文章你给几分