def get_translations(languages=None, getter=get_builtin_gnu_translations):
"""
Get a WTForms translation object which wraps a low-level translations object.
:param languages:
A sequence of languages to try, in order.
:param getter:
A single-argument callable which returns a low-level translations object.
"""
translations = getter(languages)
if hasattr(translations, 'ugettext'):
return DefaultTranslations(translations)
else:
# Python 3 has no ugettext/ungettext, so just return the translations object.
return translations
python类translation()的实例源码
def resource_exists(name):
"""Return true if the given resource exists"""
try:
open_resource(name).close()
return True
except IOError:
return False
# Enable this when we get some translations?
# We want an i18n API that is useful to programs using Python's gettext
# module, as well as the Zope3 i18n package. Perhaps we should just provide
# the POT file and translations, and leave it up to callers to make use
# of them.
#
# t = gettext.translation(
# 'pytz', os.path.join(os.path.dirname(__file__), 'locales'),
# fallback=True
# )
# def _(timezone_name):
# """Translate a timezone name using the current locale, returning Unicode"""
# return t.ugettext(timezone_name)
def resource_exists(name):
"""Return true if the given resource exists"""
try:
open_resource(name).close()
return True
except IOError:
return False
# Enable this when we get some translations?
# We want an i18n API that is useful to programs using Python's gettext
# module, as well as the Zope3 i18n package. Perhaps we should just provide
# the POT file and translations, and leave it up to callers to make use
# of them.
#
# t = gettext.translation(
# 'pytz', os.path.join(os.path.dirname(__file__), 'locales'),
# fallback=True
# )
# def _(timezone_name):
# """Translate a timezone name using the current locale, returning Unicode"""
# return t.ugettext(timezone_name)
def get_translations(languages=None, getter=get_builtin_gnu_translations):
"""
Get a WTForms translation object which wraps a low-level translations object.
:param languages:
A sequence of languages to try, in order.
:param getter:
A single-argument callable which returns a low-level translations object.
"""
translations = getter(languages)
if hasattr(translations, 'ugettext'):
return DefaultTranslations(translations)
else:
# Python 3 has no ugettext/ungettext, so just return the translations object.
return translations
def test_the_alternative_interface(self):
eq = self.assertEqual
# test the alternative interface
with open(self.mofile, 'rb') as fp:
t = gettext.GNUTranslations(fp)
# Install the translation object
t.install()
eq(_('nudge nudge'), 'wink wink')
# Try unicode return type
t.install(unicode=True)
eq(_('mullusk'), 'bacon')
# Test installation of other methods
import __builtin__
t.install(unicode=True, names=["gettext", "lgettext"])
eq(_, t.ugettext)
eq(__builtin__.gettext, t.ugettext)
eq(lgettext, t.lgettext)
del __builtin__.gettext
del __builtin__.lgettext
def test_cache(self):
self.localedir = os.curdir
self.mofile = MOFILE
self.assertEqual(len(gettext._translations), 0)
t = gettext.translation('gettext', self.localedir)
self.assertEqual(len(gettext._translations), 1)
t = gettext.translation('gettext', self.localedir,
class_=DummyGNUTranslations)
self.assertEqual(len(gettext._translations), 2)
self.assertEqual(t.__class__, DummyGNUTranslations)
# Calling it again doesn't add to the cache
t = gettext.translation('gettext', self.localedir,
class_=DummyGNUTranslations)
self.assertEqual(len(gettext._translations), 2)
self.assertEqual(t.__class__, DummyGNUTranslations)
def test_the_alternative_interface(self):
eq = self.assertEqual
# test the alternative interface
with open(self.mofile, 'rb') as fp:
t = gettext.GNUTranslations(fp)
# Install the translation object
t.install()
eq(_('nudge nudge'), 'wink wink')
# Try unicode return type
t.install(unicode=True)
eq(_('mullusk'), 'bacon')
# Test installation of other methods
import __builtin__
t.install(unicode=True, names=["gettext", "lgettext"])
eq(_, t.ugettext)
eq(__builtin__.gettext, t.ugettext)
eq(lgettext, t.lgettext)
del __builtin__.gettext
del __builtin__.lgettext
def test_cache(self):
self.localedir = os.curdir
self.mofile = MOFILE
self.assertEqual(len(gettext._translations), 0)
t = gettext.translation('gettext', self.localedir)
self.assertEqual(len(gettext._translations), 1)
t = gettext.translation('gettext', self.localedir,
class_=DummyGNUTranslations)
self.assertEqual(len(gettext._translations), 2)
self.assertEqual(t.__class__, DummyGNUTranslations)
# Calling it again doesn't add to the cache
t = gettext.translation('gettext', self.localedir,
class_=DummyGNUTranslations)
self.assertEqual(len(gettext._translations), 2)
self.assertEqual(t.__class__, DummyGNUTranslations)
def get_translations(self):
if self.get_locale is None:
return None
locale = self.get_locale()
if locale is None:
return None
elif not isinstance(locale, str):
# locale might be an instance of babel.core.Locale
locale = str(locale)
if '_' in locale or '-' in locale:
# If the locale has territory (e.g. 'ko_KR')
# we can search the proper match (e.g. ko_KR) and then
# the non-territory match (e.g. ko) as a fallback.
locale = locale.replace('-', '_')
locales = [locale, locale[:locale.index('_')]]
else:
locales = [locale]
return gettext.translation(
'dodotable',
os.path.join(os.path.dirname(__file__), '..', 'locale'),
fallback=True,
codeset='utf-8',
languages=locales
)
def findtranslation(self):
"Find the translation for the document language."
self.langcodes = None
if not DocumentParameters.language:
Trace.error('No language in document')
return
if not DocumentParameters.language in TranslationConfig.languages:
Trace.error('Unknown language ' + DocumentParameters.language)
return
if TranslationConfig.languages[DocumentParameters.language] == 'en':
return
langcodes = [TranslationConfig.languages[DocumentParameters.language]]
try:
self.translation = gettext.translation('elyxer', None, langcodes)
except IOError:
Trace.error('No translation for ' + unicode(langcodes))
def resource_exists(name):
"""Return true if the given resource exists"""
try:
open_resource(name).close()
return True
except IOError:
return False
# Enable this when we get some translations?
# We want an i18n API that is useful to programs using Python's gettext
# module, as well as the Zope3 i18n package. Perhaps we should just provide
# the POT file and translations, and leave it up to callers to make use
# of them.
#
# t = gettext.translation(
# 'pytz', os.path.join(os.path.dirname(__file__), 'locales'),
# fallback=True
# )
# def _(timezone_name):
# """Translate a timezone name using the current locale, returning Unicode"""
# return t.ugettext(timezone_name)
def get_translations(languages=None, getter=get_builtin_gnu_translations):
"""
Get a WTForms translation object which wraps a low-level translations object.
:param languages:
A sequence of languages to try, in order.
:param getter:
A single-argument callable which returns a low-level translations object.
"""
translations = getter(languages)
if hasattr(translations, 'ugettext'):
return DefaultTranslations(translations)
else:
# Python 3 has no ugettext/ungettext, so just return the translations object.
return translations
def initGetText(domain, install=False, fallback=True):
locale_paths = [
Path(__file__).parent / ".." / "locale",
Path(sys.prefix) / "share" / "locale",
]
locale_dir, translation = None, None
for locale_dir in [d for d in locale_paths if d.exists()]:
if gettext.find(domain, str(locale_dir)):
log.debug("Loading message catalogs from {}".format(locale_dir))
translation = gettext.translation(domain, str(locale_dir))
break
if translation is None:
# This with either throw FileNotFoundError (fallback=False) or set a
# gettext.NullTranslations
translation = gettext.translation(domain, str(locale_dir),
fallback=fallback)
assert translation
if install:
gettext.install(domain, str(locale_dir), names=["ngettext"])
return translation
def get_translations(languages=None, getter=get_builtin_gnu_translations):
"""
Get a WTForms translation object which wraps a low-level translations object.
:param languages:
A sequence of languages to try, in order.
:param getter:
A single-argument callable which returns a low-level translations object.
"""
translations = getter(languages)
if hasattr(translations, 'ugettext'):
return DefaultTranslations(translations)
else:
# Python 3 has no ugettext/ungettext, so just return the translations object.
return translations
def get_translations(languages=None, getter=get_builtin_gnu_translations):
"""
Get a WTForms translation object which wraps a low-level translations object.
:param languages:
A sequence of languages to try, in order.
:param getter:
A single-argument callable which returns a low-level translations object.
"""
translations = getter(languages)
if hasattr(translations, 'ugettext'):
return DefaultTranslations(translations)
else:
# Python 3 has no ugettext/ungettext, so just return the translations object.
return translations
def resource_exists(name):
"""Return true if the given resource exists"""
try:
open_resource(name).close()
return True
except IOError:
return False
# Enable this when we get some translations?
# We want an i18n API that is useful to programs using Python's gettext
# module, as well as the Zope3 i18n package. Perhaps we should just provide
# the POT file and translations, and leave it up to callers to make use
# of them.
#
# t = gettext.translation(
# 'pytz', os.path.join(os.path.dirname(__file__), 'locales'),
# fallback=True
# )
# def _(timezone_name):
# """Translate a timezone name using the current locale, returning Unicode"""
# return t.ugettext(timezone_name)
def resource_exists(name):
"""Return true if the given resource exists"""
try:
open_resource(name).close()
return True
except IOError:
return False
# Enable this when we get some translations?
# We want an i18n API that is useful to programs using Python's gettext
# module, as well as the Zope3 i18n package. Perhaps we should just provide
# the POT file and translations, and leave it up to callers to make use
# of them.
#
# t = gettext.translation(
# 'pytz', os.path.join(os.path.dirname(__file__), 'locales'),
# fallback=True
# )
# def _(timezone_name):
# """Translate a timezone name using the current locale, returning Unicode"""
# return t.ugettext(timezone_name)
def test_the_alternative_interface(self):
eq = self.assertEqual
# test the alternative interface
with open(self.mofile, 'rb') as fp:
t = gettext.GNUTranslations(fp)
# Install the translation object
t.install()
eq(_('nudge nudge'), 'wink wink')
# Try unicode return type
t.install()
eq(_('mullusk'), 'bacon')
# Test installation of other methods
import builtins
t.install(names=["gettext", "lgettext"])
eq(_, t.gettext)
eq(builtins.gettext, t.gettext)
eq(lgettext, t.lgettext)
del builtins.gettext
del builtins.lgettext
def test_cache(self):
self.localedir = os.curdir
self.mofile = MOFILE
self.assertEqual(len(gettext._translations), 0)
t = gettext.translation('gettext', self.localedir)
self.assertEqual(len(gettext._translations), 1)
t = gettext.translation('gettext', self.localedir,
class_=DummyGNUTranslations)
self.assertEqual(len(gettext._translations), 2)
self.assertEqual(t.__class__, DummyGNUTranslations)
# Calling it again doesn't add to the cache
t = gettext.translation('gettext', self.localedir,
class_=DummyGNUTranslations)
self.assertEqual(len(gettext._translations), 2)
self.assertEqual(t.__class__, DummyGNUTranslations)
def get_translations(languages=None, getter=get_builtin_gnu_translations):
"""
Get a WTForms translation object which wraps a low-level translations object.
:param languages:
A sequence of languages to try, in order.
:param getter:
A single-argument callable which returns a low-level translations object.
"""
translations = getter(languages)
if hasattr(translations, 'ugettext'):
return DefaultTranslations(translations)
else:
# Python 3 has no ugettext/ungettext, so just return the translations object.
return translations