千万人的失败,都有是失败在做事不彻底,往往做到离成功只差一步就终止不做了。
一般地,一个大型的项目,特别是一个跨国平台,都需要进行国际化支持。OpenStack作为一个开源的云平台方案,同样需要支持国际化。因此,OpenStack社区开发了oslo.i18n组件支持OpenStack项目的国际化。本文便简单的介绍了OpenStack支持国际化的实现与使用。
oslo.i18n的实现
OpenStack项目支持国际化的实现非常简单,在oslo.i18n中主要使用TranslatorFactory类实现国际化支持。该类中提供了primary()方法进行国际化翻译,而该类则实际调用了_make_translation_func(domain)实现具体的操作。
1 | def _make_translation_func(self, domain=None): |
在该方法中定义了两种实现国际化的方式:第一种方式是直接使用gettext模块生成一个翻译函数,输出国际化结果;而另一种方式可以理解为一种懒加载模式,如果你直接在代码中导入_
,而不是通过gettextutils.install()方式导入,这种懒加载模式将会很有用。该模式返回一个oslo.i18n自己定义的Message对象缓存待翻译的unicode编码的信息,在实例化时通过调用Message类的静态方法_translate_msgid(msgid, domain)获取对应的国际化信息。
oslo.i18n的使用
国际化支持在OpenStack各项目中使用频繁,oslo.i18n为了使用更加的方便,定义了_
表示一个TranslatorFactory对象的primary()方法,因此在使用国际化之前,首先需要导入_
;另外,在为日志支持国际化时也特意定义了_LI、_LW、_LE、_LC等不同级别的国际化支持方法。
1 | import oslo_i18n |
在使用时只需要导入这些方法的别名即可使用这些方法直接实现信息国际化的支持。
1 | from nova.i18n import _, _LE |
如上面的一段代码中,Nova组件使用_LE方法对一条异常信息进行了国际化打印的支持。
原文链接:https://blog.csdn.net/Bill_Xiang_/article/details/78570404