本文整理汇总了Python中babel.support.Translations.load方法的典型用法代码示例。如果您正苦于以下问题:Python Translations.load方法的具体用法?Python Translations.load怎么用?Python Translations.load使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类babel.support.Translations
的用法示例。
在下文中一共展示了Translations.load方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load_gettext_translations
# 需要导入模块: from babel.support import Translations [as 别名]
# 或者: from babel.support.Translations import load [as 别名]
def load_gettext_translations(directory, domain):
"""Loads translations from gettext's locale tree"""
global _translations
global _supported_locales
global _use_gettext
_translations = {}
for lang in os.listdir(directory):
if lang.startswith('.'):
continue # skip .svn, etc
if os.path.isfile(os.path.join(directory, lang)):
continue
try:
# Load existing translation or Null Translations
translation = _translations.get(lang, Translations.load())
if isinstance(translation, gettext.NullTranslations):
_translations[lang] = Translations.load(
directory, [lang], domain
)
else:
_translations[lang].merge(
Translations.load(directory, [lang], domain)
)
except Exception, e:
logging.error("Cannot load translation for '%s': %s", lang, str(e))
continue
示例2: get_translations
# 需要导入模块: from babel.support import Translations [as 别名]
# 或者: from babel.support.Translations import load [as 别名]
def get_translations(self):
"""Returns the correct gettext translations that should be used for
this request. This will never fail and return a dummy translation
object if used outside of the request or if a translation cannot be
found.
"""
ctx = stack.top
if ctx is None:
return NullTranslations()
locale = get_locale()
cache = self.get_translations_cache(ctx)
translations = cache.get(str(locale))
if translations is None:
translations_dir = self.get_translations_path(ctx)
translations = Translations.load(translations_dir, locale, domain=self.domain)
# Load plugins translations
if isinstance(translations, Translations):
for plugin_name in current_app.config['PLUGINS']:
module_name = 'udata.ext.{0}'.format(plugin_name)
module = import_module(module_name)
translations_dir = join(dirname(module.__file__), 'translations')
if exists(translations_dir):
domain = '-'.join((self.domain, plugin_name))
plugins_translations = Translations.load(translations_dir, locale, domain=domain)
translations.merge(plugins_translations)
cache[str(locale)] = translations
return translations
示例3: get_translations
# 需要导入模块: from babel.support import Translations [as 别名]
# 或者: from babel.support.Translations import load [as 别名]
def get_translations(self):
"""Returns the correct gettext translations that should be used for
this request. This will never fail and return a dummy translation
object if used outside of the request or if a translation cannot be
found.
"""
ctx = stack.top
if ctx is None:
return NullTranslations()
locale = get_locale()
cache = self.get_translations_cache(ctx)
translations = cache.get(str(locale))
if translations is None:
translations_dir = self.get_translations_path(ctx)
translations = Translations.load(translations_dir, locale,
domain=self.domain)
# Load plugins translations
if isinstance(translations, Translations):
# Load core extensions translations
from wtforms.i18n import messages_path
wtforms_translations = Translations.load(messages_path(),
locale,
domain='wtforms')
translations.merge(wtforms_translations)
import flask_security
flask_security_translations = Translations.load(
join(flask_security.__path__[0], 'translations'),
locale,
domain='flask_security'
)
translations.merge(flask_security_translations)
for pkg in entrypoints.get_roots(current_app):
package = pkgutil.get_loader(pkg)
path = join(package.filename, 'translations')
domains = [f.replace(path, '').replace('.pot', '')[1:]
for f in iglob(join(path, '*.pot'))]
for domain in domains:
translations.merge(Translations.load(path, locale,
domain=domain))
# Allows the theme to provide or override translations
from . import theme
theme_translations_dir = join(theme.current.path, 'translations')
if exists(theme_translations_dir):
domain = theme.current.identifier
theme_translations = Translations.load(theme_translations_dir,
locale,
domain=domain)
translations.merge(theme_translations)
cache[str(locale)] = translations
return translations
示例4: new_translator
# 需要导入模块: from babel.support import Translations [as 别名]
# 或者: from babel.support.Translations import load [as 别名]
def new_translator(languages=None):
lang = languages or LANGUAGES
translations = Translations.load(dirname(__file__), lang, 'weckan')
if not isinstance(translations, Translations):
return translations
for name, path in EXTRA_TRANSLATIONS:
translations.merge(Translations.load(path, lang, name))
return translations
示例5: _get_translation_for_locale
# 需要导入模块: from babel.support import Translations [as 别名]
# 或者: from babel.support.Translations import load [as 别名]
def _get_translation_for_locale(self, locale):
"""Get translation for a specific locale."""
translations = None
for dirname in self.paths:
# Load a single catalog.
catalog = Translations.load(dirname, [locale], domain=self.domain)
if translations is None:
if isinstance(catalog, NullTranslations):
translations = catalog
continue
try:
# Merge catalog into global catalog
translations.merge(catalog)
except AttributeError:
# Translations is probably NullTranslations
if isinstance(catalog, NullTranslations):
current_app.logger.debug(
"Compiled translations seems to be missing"
" in {0}.".format(dirname))
continue
raise
return translations or NullTranslations()
示例6: load_translation
# 需要导入模块: from babel.support import Translations [as 别名]
# 或者: from babel.support.Translations import load [as 别名]
def load_translation(self,langs, dirname, domain):
"""Loads the first existing translations for known locale and saves the
`Lang` object in a global cache for faster lookup on the next request.
:parameters:
langs : List
List of languages as returned by `parse_accept_language_header`.
dirname : String
Directory of the translations (`tools.I18nTool.mo_dir`).
domain : String
Gettext domain of the catalog (`tools.I18nTool.domain`).
:returns: Lang object with two attributes (Lang.trans = the translations
object, Lang.locale = the corresponding Locale object).
:rtype: Lang
:raises: ImproperlyConfigured if no locale where known.
"""
locale = None
for lang in langs:
short = lang[:2].lower()
try:
locale = Locale.parse(lang)
if (domain, short) in _languages:
return _languages[(domain, short)]
trans = Translations.load(dirname, short, domain)
except (ValueError, UnknownLocaleError):
continue
# If the translation was found, exit loop
if isinstance(trans, Translations):
break
if locale is None:
raise ImproperlyConfigured('Default locale not known.')
_languages[(domain, short)] = res = Lang(locale, trans)
return res
示例7: run
# 需要导入模块: from babel.support import Translations [as 别名]
# 或者: from babel.support.Translations import load [as 别名]
def run(self, root):
i18n_dir = self.extension.getConfig('i18n_dir')
pot_path = os.path.join(i18n_dir, 'messages.pot')
if os.path.exists(pot_path):
with open(pot_path, 'r') as f:
catalog = pofile.read_po(f)
else:
catalog = Catalog()
lang = self.extension.getConfig('i18n_lang')
mo_path = os.path.join(i18n_dir, lang, 'LC_MESSAGES', 'messages.mo')
po_path = os.path.join(i18n_dir, lang, 'LC_MESSAGES', 'messages.po')
if os.path.exists(po_path):
with open(po_path, 'r') as f:
lang_catalog = pofile.read_po(f)
with open(mo_path, 'w') as mo:
mofile.write_mo(mo, lang_catalog)
translations = Translations.load(i18n_dir, locales=[lang])
self.translate(catalog, translations, root)
with open(pot_path, 'w') as pot_file:
pofile.write_po(pot_file, catalog)
示例8: runTest
# 需要导入模块: from babel.support import Translations [as 别名]
# 或者: from babel.support.Translations import load [as 别名]
def runTest(self):
"""Test for regression of http://trac.edgewall.org/ticket/11515
Show a notice message with new language setting after it is changed.
"""
from trac.util.translation import has_babel, get_available_locales
from pkg_resources import resource_exists, resource_filename
if not has_babel:
return
if not resource_exists("trac", "locale"):
return
locale_dir = resource_filename("trac", "locale")
from babel.support import Translations
string = "Your preferences have been saved."
translated = None
for second_locale in get_available_locales():
tx = Translations.load(locale_dir, second_locale)
translated = tx.dgettext("messages", string)
if string != translated:
break # the locale has a translation
else:
return
try:
self._tester.go_to_preferences("Language")
tc.formvalue("userprefs", "language", second_locale)
tc.submit()
tc.find(re.escape(translated))
finally:
tc.formvalue("userprefs", "language", "") # revert to default
tc.submit()
tc.find("Your preferences have been saved")
示例9: get_translations
# 需要导入模块: from babel.support import Translations [as 别名]
# 或者: from babel.support.Translations import load [as 别名]
def get_translations(locale):
"""Get the translation for a locale."""
locale = Locale.parse(locale)
translations = _translations.get(str(locale))
if translations is not None:
return translations
rv = Translations.load(os.path.dirname(__file__), [locale])
_translations[str(locale)] = rv
return rv
示例10: pre_process_request
# 需要导入模块: from babel.support import Translations [as 别名]
# 或者: from babel.support.Translations import load [as 别名]
def pre_process_request(self, req, handler):
try:
from babel.support import Translations
from pkg_resources import resource_filename
global translations
translations = Translations.load(resource_filename(__name__, 'locale'), req.locale)
except ImportError:
pass
return handler
示例11: load_translations
# 需要导入模块: from babel.support import Translations [as 别名]
# 或者: from babel.support.Translations import load [as 别名]
def load_translations(import_name, locale):
"""Loads gettext translations for the given locale from the specified
package represented by the given import name.
"""
if import_name not in sys.modules:
return None
path = os.path.abspath(os.path.dirname(sys.modules[import_name].__file__))
path = os.path.join(path, 'locale')
return Translations.load(path, [locale])
示例12: setup_i18n
# 需要导入模块: from babel.support import Translations [as 别名]
# 或者: from babel.support.Translations import load [as 别名]
def setup_i18n( self ):
if 'HTTP_ACCEPT_LANGUAGE' in self.environ:
# locales looks something like: ['en', 'en-us;q=0.7', 'ja;q=0.3']
locales = self.environ['HTTP_ACCEPT_LANGUAGE'].split( ',' )
locales = [ l.split( ';' )[0] for l in locales ]
else:
# Default to English
locales = 'en'
t = Translations.load( dirname='locale', locales=locales, domain='ginga' )
self.template_context.update ( dict( _=t.ugettext, n_=t.ugettext, N_=t.ungettext ) )
示例13: activate
# 需要导入模块: from babel.support import Translations [as 别名]
# 或者: from babel.support.Translations import load [as 别名]
def activate(self, locale, env_path=None):
try:
locale_dir = pkg_resources.resource_filename("trac", "locale")
except Exception:
self._activate_failed = True
return
t = Translations.load(locale_dir, locale or "en_US")
if not t or t.__class__ is NullTranslations:
t = self._null_translations
elif env_path:
self._plugin_domains_lock.acquire()
try:
domains = list(self._plugin_domains.get(env_path, []))
finally:
self._plugin_domains_lock.release()
for domain, dirname in domains:
t.add(Translations.load(dirname, locale, domain))
self._current.translations = t
self._activate_failed = False
示例14: activate
# 需要导入模块: from babel.support import Translations [as 别名]
# 或者: from babel.support.Translations import load [as 别名]
def activate(self, locale, env_path=None):
try:
locale_dir = pkg_resources.resource_filename("trac", "locale")
except Exception:
self._activate_failed = True
return
t = Translations.load(locale_dir, locale or "en_US")
if not isinstance(t, Translations):
t = self._null_translations
else:
self._add(t, Translations.load(locale_dir, locale or "en_US", "tracini"))
if env_path:
with self._plugin_domains_lock:
domains = self._plugin_domains.get(env_path, {})
domains = domains.items()
for domain, dirname in domains:
self._add(t, Translations.load(dirname, locale, domain))
self._current.translations = t
self._activate_failed = False
示例15: setup_i18n
# 需要导入模块: from babel.support import Translations [as 别名]
# 或者: from babel.support.Translations import load [as 别名]
def setup_i18n(self):
if "HTTP_ACCEPT_LANGUAGE" in self.environ:
# locales looks something like: ['en', 'en-us;q=0.7', 'ja;q=0.3']
locales = self.environ["HTTP_ACCEPT_LANGUAGE"].split(",")
locales = [l.split(";")[0] for l in locales]
else:
# Default to English
locales = "en"
t = Translations.load(dirname="locale", locales=locales, domain="ginga")
self.template_context.update(dict(_=t.ugettext, n_=t.ugettext, N_=t.ungettext))