osloi18n(1)

OSLOI18N(1) oslo.i18n OSLOI18N(1)

NAME

osloi18n - oslo.i18n 6.0.0

The oslo.i18n library contain utilities for working with internationalization (i18n) features, especially translation for text strings in an application or library.

CONTENTS

Using oslo.i18n

How to Use oslo.i18n in Your Application or Library

Installing

At the command line:

$ pip install oslo.i18n


Creating an Integration Module

To use oslo.i18n in a project (e.g. myapp), you will need to create a small integration module to hold an instance of TranslatorFactory and references to the marker functions the factory creates.

NOTE:

Libraries probably do not want to expose the new integration module as part of their public API, so rather than naming it myapp.i18n it should be called myapp._i18n to indicate that it is a private implementation detail, and not meant to be used outside of the library's own code.


NOTE:

Starting with the Pike series, OpenStack no longer supports log translation. It is not necessary to add translation instructions to new code, and the instructions can be removed from old code. Refer to the email thread understanding log domain change on the openstack-dev mailing list for more details.


# myapp/_i18n.py
import oslo_i18n
DOMAIN = "myapp"
_translators = oslo_i18n.TranslatorFactory(domain=DOMAIN)
# 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
def get_available_languages():

return oslo_i18n.get_available_languages(DOMAIN)


Then, in the rest of your code, use the appropriate marker function for each message:

from myapp._i18n import _
# ...
variable = "openstack"
some_object.name_msg = _('my name is: %s') % variable
# ...
try:

# ... except AnException1:
# Log only, log messages are no longer translated
LOG.exception('exception message') except AnException2:
# Raise only
raise RuntimeError(_('exception message')) else:
# Log and Raise
msg = _('Unexpected error message')
LOG.exception(msg)
raise RuntimeError(msg)


NOTE:

The import of multiple modules from _i18n on a single line is a valid exception to OpenStack Style Guidelines for import statements.


It is important to use the marker functions (e.g. _), rather than the longer form of the name, because the tool that scans the source code for translatable strings looks for the marker function names.

WARNING:

The old method of installing a version of _() in the builtins namespace is deprecated. Modifying the global namespace affects libraries as well as the application, so it may interfere with proper message catalog lookups. Calls to gettextutils.install() should be replaced with the application or library integration module described here.


Handling hacking Objections to Imports

The OpenStack Style Guidelines prefer importing modules and accessing names from those modules after import, rather than importing the names directly. For example:

# WRONG
from foo import bar
bar()
# RIGHT
import foo
foo.bar()


The linting tool hacking will typically complain about importing names from within modules. It is acceptable to bypass this for the translation marker functions, because they must have specific names and their use pattern is dictated by the message catalog extraction tools rather than our style guidelines. To bypass the hacking check for imports from this integration module, add an import exception to tox.ini.

For example:

# tox.ini
[hacking]
import_exceptions = myapp._i18n


Lazy Translation

Lazy translation delays converting a message string to the translated form as long as possible, including possibly never if the message is not logged or delivered to the user in some other way. It also supports logging translated messages in multiple languages, by configuring separate log handlers.

Lazy translation is implemented by returning a special object from the translation function, instead of a unicode string. That special message object supports some, but not all, string manipulation APIs. For example, concatenation with addition is not supported, but interpolation of variables is supported. Depending on how translated strings are used in an application, these restrictions may mean that lazy translation cannot be used, and so it is not enabled by default.

To enable lazy translation, call enable_lazy().

import oslo_i18n
oslo_i18n.enable_lazy()


Translating Messages

Use translate() to translate strings to a specific locale. translate() handles delayed translation and strings that have already been translated immediately. It should be used at the point where the locale to be used is known, which is often just prior to the message being returned or a log message being emitted.

import oslo_i18n
trans_msg = oslo_i18n.translate(msg, my_locale)


If a locale is not specified the default locale is used.

Available Languages

Only the languages that have translations provided are available for translation. To determine which languages are available the get_available_languages() is provided. The integration module provides a domain defined specific function.

import myapp._i18n
languages = myapp._i18n.get_available_languages()


SEE ALSO:

guidelines



Displaying translated messages

Several preparations are required to display translated messages in your running application.

Preferred language
You need to specify your preferred language through an environment variable. The preferred language can be specified by LANGUAGE, LC_ALL, LC_MESSAGES, or LANGUAGE (A former one has a priority).

oslo_i18n.translate() can be used to translate a string to override the preferred language.

NOTE:

You need to use enable_lazy() to override the preferred language by using oslo_i18n.translate().


Locale directory
Python gettext looks for binary mo files for the given domain using the path <localedir>/<language>/LC_MESSAGES/<domain>.mo. The default locale directory varies on distributions, and it is /usr/share/locale in most cases.

If you store message catalogs in a different location, you need to specify the location via an environment variable named <DOMAIN>_LOCALEDIR where <DOMAIN> is an upper-case domain name with replacing _ and . with -. For example, NEUTRON_LOCALEDIR for a domain neutron and OSLO_I18N_LOCALEDIR for a domain oslo_i18n.

NOTE:

When you specify locale directories via <DOMAIN>_LOCALEDIR environment variables, you need to specify an environment variable per domain. More concretely, if your application using a domain myapp` uses oslo.policy, you need to specify both ``MYAPP_LOCALEDIR and OSLO_POLICY_LOCALEDIR to ensure that translation messages from both your application and oslo.policy are displayed.



Guidelines for Use in OpenStack

The OpenStack I18N team has a limited capacity to translate messages, so we want to make their work as effective as possible by identifying the most useful text for them to translate. All text messages the user sees via exceptions or API calls should be marked for translation. However, some exceptions are used internally to signal error conditions between modules and are not intended to be presented to the user. Those do not need to be translated. Neither do log messages, as explained below.

SEE ALSO:

  • usage
  • api



Gettext Contextual Form and Plural Form

Sometimes under different contexts, the same word should be translated into different phrases using TranslatorFactory.contextual_form.

And recommend the following code to use contextual form:

# The contextual translation function using the name "_C"
_C = _translators.contextual_form
...
msg = _C('context', 'string')


In some languages, sometimes the translated strings are different with different item counts using TranslatorFactory.plural_form

And recommend the following code to use plural form:

# The plural translation function using the name "_P"
_P = _translators.plural_form
...
msg = _P('single', 'plural', count)


The contextual form and plural form are used only when needed. By default, the translation should use the _().

NOTE:

These two functions were only available in oslo.i18n >= 2.1.0.


Log Translation

NOTE:

Starting with the Pike series, OpenStack no longer supports log translation. It is not necessary to add translation instructions to new code, and the instructions can be removed from old code. The following documentation is retained to help developers understand existing usage and how to remove it.

Support was dropped primarily based on feedback from operators that they were not only not needed but also undesirable, because they fragmented the set of web pages providing helpful information about any particular log message, thereby reducing the chances of finding those web pages by doing a web search for the message. Refer to the email thread understanding log domain change on the openstack-dev mailing list for more details.



OpenStack previously supported translating some log levels using separate message catalogs, and so has separate marker functions. These well-known names were used by the build system jobs that extracted the messages from the source code and passed them to the translation tool.

Level Function
INFO _LI()
WARNING _LW()
ERROR _LE()
CRITICAL _LC()

NOTE:

Debug level log messages were never translated.


Using a Marker Function

The marker functions are used to mark the translatable strings in the code. The strings are extracted into catalogs using a tool that performs source inspection to look for these specific markers, so the function argument must just be a string.

For example: do not do this:

# WRONG
msg = _(variable_containing_msg)


Instead, use this style:

# RIGHT
msg = _('My message.')


Choosing a Marker Function

The purpose of the different marker functions is to separate the translatable messages into different catalogs, which the translation teams can prioritize translating. It is important to choose the right marker function, to ensure that strings the user sees will be translated and to help the translation team manage their work load.

Everything marked with _() will be translated. Prioritizing the catalogs created from strings marked with the log marker functions is up to the individual translation teams and their users, but it is expected that they will work on critical and error messages before warning or info.

_() is preferred for any user facing message, even if it is also going to a log file. This ensures that the translated version of the message will be available to the user.

The log marker functions (_LI(), _LW(), _LE(), and _LC()) should no longer be used, and existing usages should be removed. Anytime that the message is passed outside of the current context (for example as part of an exception) the _() marker function must be used instead.

A common pattern used to be to define a single message object and use it more than once, for the log call and the exception. In that case, _() had to be used because the message was going to appear in an exception that may be presented to the user.

However, now that log messages are no longer translated, it is unfortunately necessary to use two separate strings: a plain one for the log message, and a translatable one for the exception.

For example, do not do this:

# WRONG
msg = _('There was an error.')
LOG.error(msg)
raise LocalExceptionClass(msg)


or this:

# EVEN MORE WRONG
msg = _LE('There was an error.')
LOG.error(msg)
raise LocalExceptionClass(msg)


Instead, use this style:

# RIGHT
LOG.error('There was an error.')
raise LocalExceptionClass(_('An error occurred.'))


Adding Variables to Translated Messages

Translated messages should not be combined with other literal strings to create partially translated messages. For example, do not do this:

# WRONG
raise ValueError(_('some message') + ': variable=%s' % variable)


Instead, use this style:

# RIGHT
raise ValueError(_('some message: variable=%s') % variable)


Including the variable reference inside the translated message allows the translator to take into account grammar rules, differences in left-right vs. right-left rendering, and other factors to make the translated message more useful to the end user.

Any message with more than one variable should use named interpolation instead of positional, to allow translators to move the variables around in the string to account for differences in grammar and writing direction.

For example, do not do this:

# WRONG
raise ValueError(_('some message: v1=%s v2=%s') % (v1, v2))


Instead, use this style:

# RIGHT
raise ValueError(_('some message: v1=%(v1)s v2=%(v2)s') % {'v1': v1, 'v2': v2})


CHANGES

6.0.0

  • Imported Translations from Zanata
  • Fix formatting of release list
  • Drop python3.6/3.7 support in testing runtime
  • Remove unnecessary unicode prefixes
  • Update CI to use unversioned jobs template
  • setup.cfg: Replace dashes by underscores

5.1.0

  • Changed minversion in tox to 3.18.0
  • Switch testing to Xena testing runtime
  • Upgrade the pre-commit-hooks version
  • Fix requirements issues
  • Remove all usage of six library
  • Use TOX_CONSTRAINTS_FILE
  • Use py3 as the default runtime for tox
  • Fix hacking min version to 3.0.1
  • Remove six.PY3
  • Adding pre-commit
  • Add Python3 wallaby unit tests
  • Update master for stable/victoria

5.0.1

Bump bandit version

5.0.0

  • Stop to use the __future__ module
  • Remove a couple more shim tests
  • Imported Translations from Zanata
  • Remove Message.translate
  • Add Babel aliases to get_available_languages
  • Switch to newer openstackdocstheme and reno versions
  • Remove the unused coding style modules
  • Remove translation sections from setup.cfg
  • Align contributing doc with oslo's policy
  • Bump default tox env from py37 to py38
  • Add py38 package metadata
  • Drop use of babel
  • Add release notes links to doc index
  • Add Python3 victoria unit tests
  • Update master for stable/ussuri

4.0.1

  • Use unittest.mock instead of third party mock
  • Update hacking for Python3

4.0.0

  • remove outdated header
  • [ussuri][goal] Drop python 2.7 support and testing
  • tox: Trivial cleanup

3.25.1

  • Imported Translations from Zanata
  • Integrate sphinxcontrib-apidoc

3.25.0

  • tox: Keeping going with docs
  • Update master for stable/train
  • Deprecate Message.translate in favor of Message.translation
  • Allow Message.translate to handle unhashable inputs

3.24.0

  • Add Python 3 Train unit tests
  • Move doc related modules to doc/requirements.txt
  • Clarify that translation strings are extracted via source inspection
  • Fix guidelines w.r.t. translation of log messages
  • Move to releases.openstack.org
  • Cap Bandit below 1.6.0 and update Sphinx requirement
  • Replace git.openstack.org URLs with opendev.org URLs
  • OpenDev Migration Patch
  • Dropping the py35 testing
  • Update master for stable/stein

3.23.1

  • add python 3.7 unit test job
  • Change python3.5 job to python3.7 job on Stein+
  • Update hacking version
  • Update mailinglist from dev to discuss

3.23.0

  • Override getttext.find to cache result
  • Don't quote {posargs} in tox.ini
  • Clean up .gitignore references to personal tools
  • Always build universal wheels
  • Remove references to log translation functions
  • Use templates for cover and lower-constraints

3.22.1

  • Remove unused code
  • Imported Translations from Zanata
  • add lib-forward-testing-python3 test job
  • add python 3.6 unit test job
  • import zuul job settings from project-config
  • Update reno for stable/rocky

3.21.0

  • Switch to stestr
  • Add release notes to README.rst
  • fix tox python3 overrides
  • Remove moxstubout usage
  • Remove stale pip-missing-reqs tox test
  • Trivial: Update pypi url to new url
  • set default python to python3
  • add lower-constraints job
  • Updated from global requirements

3.20.0

  • Imported Translations from Zanata
  • Update links in README
  • Imported Translations from Zanata
  • Update reno for stable/queens
  • Updated from global requirements
  • Updated from global requirements
  • Updated from global requirements

3.19.0

  • Remove -U from pip install
  • Avoid tox_install.sh for constraints support
  • add bandit to pep8 job
  • Updated from global requirements
  • Remove setting of version/release from releasenotes
  • Updated from global requirements
  • Imported Translations from Zanata
  • Updated from global requirements

3.18.0

  • Updated from global requirements
  • Updated from global requirements
  • Imported Translations from Zanata
  • Update reno for stable/pike
  • Updated from global requirements

3.17.0

  • Imported Translations from Zanata
  • Update URLs in documents according to document migration

3.16.0

  • switch from oslosphinx to openstackdocstheme
  • turn on warning-is-error in doc build
  • rearrange the documentation to fit into the new standard layout
  • Updated from global requirements
  • Enable some off-by-default checks
  • Updated from global requirements
  • Updated from global requirements
  • Updated from global requirements

3.15.3

Revert "Remove Babel as a runtime requirement"

3.15.2

  • Updated from global requirements
  • Remove Babel as a runtime requirement

3.15.1

  • Updated from global requirements
  • Updated from global requirements
  • Updated from global requirements
  • Check reStructuredText documents for common style issues

3.15.0

  • add notes about skipping log translation setup
  • Updated from global requirements

3.14.0

Python 3.5 is added

3.13.0

  • Updated from global requirements
  • [Fix gate]Update test requirement
  • Fix wrong response with language zh-TW
  • Updated from global requirements
  • Update reno for stable/ocata

3.12.0

  • Add Constraints support
  • Show team and repo badges on README
  • Replace six.iteritems() with .items()

3.11.0

  • Updated from global requirements
  • Updated from global requirements
  • Updated from global requirements
  • Add reno for release notes management
  • Add missing dependency testscenarios
  • Typo fix in oslo.i18n
  • Changed the home-page link
  • Add docs on how to display translated strings in your app

3.10.0

Updated from global requirements

3.9.0

  • Updated from global requirements
  • Fix parameters of assertEqual are misplaced

3.8.0

  • Updated from global requirements
  • Don't include openstack/common in flake8 exclude list
  • Updated from global requirements

3.7.0

  • Imported Translations from Zanata
  • Updated from global requirements

3.6.0

  • Updated from global requirements
  • Updated from global requirements
  • Better isolate tests and fixtures from environment
  • Updated from global requirements

3.4.0

Imported Translations from Zanata

3.3.0

  • Update translation setup
  • Updated from global requirements
  • Imported Translations from Zanata
  • Updated from global requirements

3.2.0

  • Updated from global requirements
  • add versionadded designations to newer functions
  • doc: contextual/plural translation requires oslo.i18n >=2.1.0
  • Trival: Remove 'MANIFEST.in'

3.1.0

  • [doc] Update _i18n.py example to pass pep8
  • Add missing blank in usage.rst
  • Remove Python 2.6 workround for logging
  • Drop python 2.6 support

3.0.0

  • Updated from global requirements
  • Remove python 2.6 classifier
  • Remove python 2.6 and cleanup tox.ini
  • Improved integration module documentation
  • Updated from global requirements
  • Imported Translations from Zanata

2.7.0

  • Fix coverage configuration and execution
  • No need for Oslo Incubator Sync
  • Enhance the formatting error robustness patch
  • Imported Translations from Zanata
  • Move 'history' -> release notes section
  • Add shields.io version/downloads links/badges into README.rst
  • Change ignore-errors to ignore_errors
  • Added the home-page value with Oslo wiki
  • Updated from global requirements

2.6.0

  • Updated from global requirements
  • Updated from global requirements

2.5.0

Trap formatting errors

2.4.0

  • Imported Translations from Transifex
  • Updated from global requirements
  • Imported Translations from Transifex
  • Updated from global requirements
  • Clean up _translate_msgid logic a bit

2.3.0

  • Imported Translations from Transifex
  • Updated from global requirements

2.2.0

  • Imported Translations from Transifex
  • Updated from global requirements
  • Updated from global requirements
  • Updated from global requirements
  • Updated from global requirements
  • Fix mock use for 1.1.0
  • Add requirements for pre-release test scripts
  • Imported Translations from Transifex

2.1.0

  • Only define CONTEXT_SEPARATOR once
  • Support contextual and plural form of gettext functions
  • Imported Translations from Transifex
  • clarify translation policy
  • Add tox target to find missing requirements
  • Imported Translations from Transifex

2.0.0

  • Updated from global requirements
  • Updated from global requirements
  • Remove oslo namespace package

1.7.0

  • Advertise support for Python3.4 / Remove support for Python 3.3
  • Updated from global requirements
  • Misplaced parenthesis causing confusion
  • Remove run_cross_tests.sh
  • Imported Translations from Transifex

1.6.0

  • Uncap library requirements for liberty
  • Standardize setup.cfg summary for oslo libs
  • Updated from global requirements
  • Move to hacking 0.10
  • Update guideline doc of multiple use msg case

1.5.0

Updated from global requirements

1.4.0

Add test fixture to prefix lazily translated messages

1.3.1

  • Clear global cache in test_get_available_languages
  • Make setup.cfg packages include oslo.i18n
  • Improve fixture documentation

1.3.0

  • Add a fixture to let tests manage the lazy flag
  • Fix the link to the bug tracker in the README

1.2.0

  • Correct the translation domain for loading messages
  • Move out of the oslo namespace package
  • Workflow documentation is now in infra-manual
  • Force code sample to be treated as python

1.1.0

  • Imported Translations from Transifex
  • Add note for integration modules in libraries
  • Activate pep8 check that _ is imported
  • Add pbr to installation requirements
  • Updated from global requirements
  • Updated from global requirements
  • Remove extraneous vim editor configuration comments
  • Make clear in docs to use _LE() when using LOG.exception()
  • Support building wheels (PEP-427)
  • Imported Translations from Transifex
  • Fix coverage testing
  • Imported Translations from Transifex
  • Use same indentation in doc/source/usage
  • Imported Translations from Transifex
  • Imported Translations from Transifex
  • Updated from global requirements
  • Remove unused/mutable default args
  • Fixes a small syntax error in the doc examples

1.0.0

Add missing six dependency

0.3.0

  • Imported Translations from Transifex
  • Work toward Python 3.4 support and testing
  • Updated from global requirements
  • Imported Translations from Transifex
  • Document how to add import exceptions

0.2.0

  • Add a test fixture for translatable strings
  • Imported Translations from Transifex
  • Remove mention of Message objects from public docs
  • Add Changelog to the documentation

0.1.0

  • Shift public API to top level package
  • Add links to policy discussions
  • Improve initial documentation
  • Update sphinx and hacking requirements
  • Fix import grouping in tests
  • Build locale dir env var name consistently
  • Updated from global requirements
  • Remove Babel version workaround code
  • Trivial refactors for gettextutils
  • Setup for translation
  • Update the public API of the library
  • Check the lazy flag at runtime
  • Handle . and - in translation domains
  • Split up monolithic test file
  • Updated from global requirements
  • Fix up usage instructions
  • fix docstring for fakes module
  • Update default tox settings
  • update .gitreview
  • update tests for python 3
  • sync cross-test script from incubator
  • pep8 fixes from import
  • update .gitignore with new lib name
  • Make unit tests pass
  • initial export with graduate.sh
  • Add API for creating translation functions
  • Use oslotest instead of common test module
  • Fix test_gettextutils on Python 3
  • Fix gettextutil.Message handling of deep copy failures
  • Change lazy translation to retain complete dict
  • Remove requirements.txt from .gitignore
  • Add etc/openstack.conf.sample to .gitignore
  • Add support for translating log levels separately
  • Fix E501 in individual openstack projects
  • Fix test method use
  • Make Message keep string interpolation args
  • Add support for locales missing from babel
  • Allow the Message class to have non-English default locales
  • Implementation of translation log handler
  • Use hacking import_exceptions for gettextutils._
  • Translation Message improvements
  • Fix violations of H302:import only modules
  • Fixed misspellings of common words
  • Trivial: Make vertical white space after license header consistent
  • Remove vim header
  • Use six.text_type instead of unicode function in tests
  • Fix typos in oslo
  • Adjust import order according to PEP8 imports rule
  • Replace assertEquals with assertEqual
  • When translating if no locale is given use default locale
  • Type check for Message param to avoid AttributeError
  • gettextutils: port to Python 3
  • Translate all substitution elements of a Message object
  • python3: Fix UserString import
  • Replace using tests.utils part2
  • Enable multiple translation domains for gettextutils
  • Bump hacking to 0.7.0
  • Allow mapping _ to lazy gettext path
  • Fix Message format-string parsing
  • Add common methods required to allow translation of REST API responses
  • Add eclipse project files to .gitignore
  • Add more robust gettext interpolation handling
  • Add .testrepository to .gitignore
  • python3: Add basic python3 compatibility
  • Enable hacking H404 test
  • Add basic lazy gettext implementation
  • Ignore backup files in .gitignore
  • Support overriding oslo localedir too
  • Add a gettextutils.install() helper function
  • gettextutils: fix translation domain
  • Fix Copyright Headers - Rename LLC to Foundation
  • Add join_consumer_pool() to RPC connections
  • Replace direct use of testtools BaseTestCase
  • Use testtools as test base class
  • Fixes import order errors
  • Add common base weigher/weigher handler for filter scheduler
  • updating sphinx documentation
  • Correcting openstack-common mv to oslo-incubator
  • Update .gitreview for oslo
  • .gitignore updates for generated files
  • Add gettext support
  • Updated tox config for multi-python testing
  • Added .gitreview file
  • ignore cover's html directory
  • Rajaram/Vinkesh|increased tests for Request and Response serializers
  • Rajaram/Vinkesh|Added nova's serializaiton classes into common
  • Initial skeleton project

oslo.i18n API Reference

oslo_i18n

oslo_i18n package

Submodules

oslo_i18n.fixture module

Test fixtures for working with oslo_i18n.

class oslo_i18n.fixture.PrefixLazyTranslation(languages=None, locale=None)
Bases: fixtures.fixture.Fixture

Fixture to prefix lazy translation enabled messages

Use of this fixture will cause messages supporting lazy translation to be replaced with the message id prefixed with 'domain/language:'. For example, 'oslo/en_US: message about something'. It will also override the available languages returned from oslo_18n.get_available_languages to the specified languages.

This will enable tests to ensure that messages were translated lazily with the specified language and not immediately with the default language.

NOTE that this does not work unless lazy translation is enabled, so it uses the ToggleLazy fixture to enable lazy translation.

Parameters
languages (list of strings) -- list of languages to support. If not specified (None) then ['en_US'] is used.

setUp()
Prepare the Fixture for use.

This should not be overridden. Concrete fixtures should implement _setUp. Overriding of setUp is still supported, just not recommended.

After setUp has completed, the fixture will have one or more attributes which can be used (these depend totally on the concrete subclass).

Raises
MultipleExceptions if _setUp fails. The last exception captured within the MultipleExceptions will be a SetupError exception.
Returns
None.
Changed in 1.3
The recommendation to override setUp has been reversed - before 1.3, setUp() should be overridden, now it should not be.
Changed in 1.3.1
BaseException is now caught, and only subclasses of Exception are wrapped in MultipleExceptions.



class oslo_i18n.fixture.ToggleLazy(enabled)
Bases: fixtures.fixture.Fixture

Fixture to toggle lazy translation on or off for a test.

setUp()
Prepare the Fixture for use.

This should not be overridden. Concrete fixtures should implement _setUp. Overriding of setUp is still supported, just not recommended.

After setUp has completed, the fixture will have one or more attributes which can be used (these depend totally on the concrete subclass).

Raises
MultipleExceptions if _setUp fails. The last exception captured within the MultipleExceptions will be a SetupError exception.
Returns
None.
Changed in 1.3
The recommendation to override setUp has been reversed - before 1.3, setUp() should be overridden, now it should not be.
Changed in 1.3.1
BaseException is now caught, and only subclasses of Exception are wrapped in MultipleExceptions.



class oslo_i18n.fixture.Translation(domain='test-domain')
Bases: fixtures.fixture.Fixture

Fixture for managing translatable strings.

This class provides methods for creating translatable strings using both lazy translation and immediate translation. It can be used to generate the different types of messages returned from oslo_i18n to test code that may need to know about the type to handle them differently (for example, error handling in WSGI apps, or logging).

Use this class to generate messages instead of toggling the global lazy flag and using the regular translation factory.

immediate(msg)
Return a string as though it had been translated immediately.
Parameters
msg (str or unicode) -- Input message string. May optionally include positional or named string interpolation markers.


lazy(msg)
Return a lazily translated message.
Parameters
msg (str or unicode) -- Input message string. May optionally include positional or named string interpolation markers.



oslo_i18n.log module

logging utilities for translation

class oslo_i18n.log.TranslationHandler(locale=None, target=None)
Bases: logging.handlers.MemoryHandler

Handler that translates records before logging them.

When lazy translation is enabled in the application (see enable_lazy()), the TranslationHandler uses its locale configuration setting to determine how to translate LogRecord objects before forwarding them to the logging.Handler.

When lazy translation is disabled, the message in the LogRecord is converted to unicode without any changes and then forwarded to the logging.Handler.

The handler can be configured declaratively in the logging.conf as follows:

[handlers]
keys = translatedlog, translator
[handler_translatedlog]
class = handlers.WatchedFileHandler
args = ('/var/log/api-localized.log',)
formatter = context
[handler_translator]
class = oslo_i18n.log.TranslationHandler
target = translatedlog
args = ('zh_CN',)


If the specified locale is not available in the system, the handler will log in the default locale.

emit(record)
Emit a record.

Append the record. If shouldFlush() tells us to, call flush() to process the buffer.


setFormatter(fmt)
Set the formatter for this handler.


Module contents

Contributing to oslo.i18n

Contributing

If you would like to contribute to the development of oslo's libraries, first you must take a look to this page:

https://specs.openstack.org/openstack/oslo-specs/specs/policy/contributing.html


If you would like to contribute to the development of OpenStack, you must follow the steps in this page:

http://docs.openstack.org/infra/manual/developers.html


Once those steps have been completed, changes to OpenStack should be submitted for review via the Gerrit tool, following the workflow documented at:

http://docs.openstack.org/infra/manual/developers.html#development-workflow


Pull requests submitted through GitHub will be ignored.

Bugs should be filed on Launchpad, not GitHub:

https://bugs.launchpad.net/oslo.i18n


Policy History

  • Discussion from Havana Summit
  • Discussion from Icehouse Summit
  • Discussion from Juno Summit
  • I18n team wiki page
  • LoggingStandards wiki page

RELEASE NOTES

Read also the oslo.i18n Release Notes.

INDICES AND TABLES

  • modindex
  • search

AUTHOR

unknown

COPYRIGHT

2023, OpenStack Foundation

October 26, 2023 6.0.0