OpenStack I18N
OpenStack I18N
官方文档:
https://docs.openstack.org/oslo.i18n/latest/user/usage.html
https://docs.openstack.org/oslo.i18n/latest/user/guidelines.html
使用前准备
准备 .mo
文件
1. 运行 Python 安装目录下的 Tools/i18n/pygettext.py
,生成 .pot
文件模版
messages.pot:
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR ORGANIZATION
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"POT-Creation-Date: 2019-10-23 13:37+0800\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: pygettext.py 1.5\n"
2. 修改 .pot
文件:写入翻译,保存为 .po
文件 (注意:无论代码中使用单引号还是双引号,.po 文件中必须用双引号)
messages.po:
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR ORGANIZATION
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"POT-Creation-Date: 2019-10-23 13:37+0800\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: pygettext.py 1.5\n"
msgid "Hello world"
msgstr "你好,世界"
3. 运行 Python 安装目录下的 Tools/i18n/msgfmt.py
,通过 .po
文件生成 .mo
文件
4. 将 .mo
文件放入文件夹 <localedir>/<language>/LC_MESSAGES/<domain>.mo
(默认为: /usr/share/locale/zh_CN/LC_MESSAGES/),文件名为程序名
在项目中使用
实例化对象
首先需要实例化一个 oslo_i18n.TranslatorFactory
对象
之后将 .primary
封装成 (_
)
在报错的字符串前使用 _
函数对字符串进行处理
import oslo_i18n as i18n
DOMAIN = 'my_app'
_translators = i18n.TranslatorFactory(domain='my_app')
# The primary translation function using the well-known name "_"
_ = _translators.primary
# The contextual translation function using the name "_C"
# requires oslo.i18n >=2.1.0
_C = _translators.contextual_form
# The plural translation function using the name "_P"
# requires oslo.i18n >=2.1.0
_P = _translators.plural_form
# 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
def translate(value, user_locale):
return i18n.translate(value, user_locale)
def get_available_languages():
return i18n.get_available_languages(DOMAIN)
翻译
将需要翻译的字符串使用 _()
处理
LOG.error('There was an error.')
raise LocalExceptionClass(_('An error occurred.'))
方法
_()
在使用 _()
函数时需要注意的是:_()
是用来标记代码中的可翻译字符串,所以应该直接传入字符串,而不是变量名
_C()
_C()
是用来进行上下文翻译的
_P()
_P()
是用来进行负数翻译的
Log Translation
官方不再支持日志翻译,如果需要翻译使用 _
即可
之前支持的
LOG.INFO: _LI()
LOG.WARNING: _LW()
LOG.ERROR: _LE()
LOG.CRITICAL: _LC()
linux 系统语言
I18N 模块会根据 Linux 系统语言的设定,去寻找相应的语言包
查看和设置 Linux 系统语言
通过 echo $LANG
进行查看
通过 export LANG=en_US.UTF-8
进行临时修改 (即时生效,重启失效)
通过修改配置文件 /etc/locale.conf
可以永久生效,需要 source /etc/locale.conf
使其立即生效