本文整理汇总了Python中babel.support.Translations类的典型用法代码示例。如果您正苦于以下问题:Python Translations类的具体用法?Python Translations怎么用?Python Translations使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Translations类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_translations
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
示例2: load_gettext_translations
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
示例3: get_translations
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
示例4: __init__
def __init__(self, fileobj=None, locale=None):
self.lang = locale
self._catalog = {}
try:
TranslationsBase.__init__(self, fileobj=fileobj)
except TypeError:
TranslationsBase.__init__(self, fp=fileobj)
if not hasattr(self, "plural"):
self.plural = lambda n: int(n != 1)
示例5: new_translator
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
示例6: lookup_translation
def lookup_translation():
ctx = _request_ctx_stack.top
if ctx is None:
return None
translations = getattr(ctx, 'pycroft_translations', None)
if translations is None:
translations = Translations()
for module in (pycroft, web):
os.path.dirname(module.__file__)
dirname = os.path.join(ctx.app.root_path, 'translations')
translations.merge(Translations.load(dirname, [get_locale()]))
ctx.pycroft_translations = translations
return translations
示例7: _parse
def _parse(self, fileobj):
TranslationsBase._parse(self, fileobj)
try:
# Got the end of file minus 4 bytes
fileobj.seek(-4, 2)
# Read stored pickled data file pointer position
pickled_data_pointer_pos = struct.unpack('i', fileobj.read())
fileobj.seek(pickled_data_pointer_pos[0])
# Load pickled data
self.client_keys.update(pickle.load(fileobj))
except EOFError:
# Catalog does not contain any pickled data at the end of it
pass
示例8: _get_translation_for_locale
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()
示例9: load_translation
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
示例10: runTest
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")
示例11: run
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)
示例12: get_translations
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
示例13: load_translations
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])
示例14: pre_process_request
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
示例15: setup_i18n
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 ) )