def get_translations(): """ Load .po file, cache .mo file repr in memory and return a Babel Translations object. This function is meant for monkey patching into Flask-Babel.""" ctx = _request_ctx_stack.top if ctx is None: return None translations_dict = ctx.app.babel_translations_dict lock = ctx.app.babel_translations_lock locale = str(get_locale()) lock.acquire() if translations_dict.get(locale) is None: mo_file = StringIO() dirname = os.path.join(ctx.app.root_path, 'translations') transfilename = os.path.join(dirname, taint_filename(locale), 'LC_MESSAGES', "messages.po") if os.path.exists(transfilename): catalog = read_po(file(transfilename, "r")) write_mo(mo_file, catalog) mo_file.seek(0) translations = Translations(fp=mo_file) else: translations = gettext.NullTranslations() translations_dict[locale] = translations else: translations = translations_dict[locale] lock.release() return translations
def test_sorting(self): # Ensure the header is sorted to the first entry so that its charset # can be applied to all subsequent messages by GNUTranslations # (ensuring all messages are safely converted to unicode) catalog = Catalog(locale='en_US') catalog.add( u'', '''\ "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n''') catalog.add(u'foo', 'Voh') catalog.add((u'There is', u'There are'), (u'Es gibt', u'Es gibt')) catalog.add(u'Fizz', '') catalog.add(('Fuzz', 'Fuzzes'), ('', '')) buf = BytesIO() mofile.write_mo(buf, catalog) buf.seek(0) translations = Translations(fp=buf) self.assertEqual(u'Voh', translations.ugettext('foo')) assert isinstance(translations.ugettext('foo'), text_type) self.assertEqual(u'Es gibt', translations.ungettext('There is', 'There are', 1)) assert isinstance(translations.ungettext('There is', 'There are', 1), text_type) self.assertEqual(u'Fizz', translations.ugettext('Fizz')) assert isinstance(translations.ugettext('Fizz'), text_type) self.assertEqual(u'Fuzz', translations.ugettext('Fuzz')) assert isinstance(translations.ugettext('Fuzz'), text_type) self.assertEqual(u'Fuzzes', translations.ugettext('Fuzzes')) assert isinstance(translations.ugettext('Fuzzes'), text_type)
def catalog_to_translations(catalog): """ Helper function which converts catalog object to translation """ buf = BytesIO() write_mo(buf, catalog, use_fuzzy=True) buf.seek(0) return Translations(fp=buf)
def run(self): mo_files = [] js_files = [] def js_path(dir, locale): return os.path.join(dir, locale + '.js') if not self.input_file: if self.locale: mo_files.append((self.locale, os.path.join(self.input_dir, self.locale, 'LC_MESSAGES', self.domain + '.mo'))) js_files.append(js_path(self.output_dir, self.locale)) else: for locale in os.listdir(self.input_dir): mo_file = os.path.join(self.input_dir, locale, 'LC_MESSAGES', self.domain + '.mo') if os.path.exists(mo_file): mo_files.append((locale, mo_file)) js_files.append(js_path(self.output_dir, locale)) else: mo_files.append((self.locale, self.input_file)) if self.output_file: js_files.append(self.output_file) else: js_files.append(js_path(self.output_dir, locale)) if not mo_files: raise DistutilsOptionError('no compiled catalogs found') if not os.path.isdir(self.output_dir): os.mkdir(self.output_dir) for idx, (locale, mo_file) in enumerate(mo_files): js_file = js_files[idx] log.info('generating messages javascript %r to %r', mo_file, js_file) infile = open(mo_file, 'rb') try: t = Translations(infile, self.domain) catalog = t._catalog finally: infile.close() outfile = open(js_file, 'w') try: write_js(outfile, catalog, self.domain, locale) finally: outfile.close()
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
def test_empty_translation_with_fallback(self): catalog1 = Catalog(locale='fr_FR') catalog1.add(u'', '''\ "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n''') catalog1.add(u'Fuzz', '') buf1 = BytesIO() mofile.write_mo(buf1, catalog1) buf1.seek(0) catalog2 = Catalog(locale='fr') catalog2.add(u'', '''\ "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n''') catalog2.add(u'Fuzz', 'Flou') buf2 = BytesIO() mofile.write_mo(buf2, catalog2) buf2.seek(0) translations = Translations(fp=buf1) translations.add_fallback(Translations(fp=buf2)) self.assertEqual(u'Flou', translations.ugettext('Fuzz'))
def load_translations(locale): """Return the translations for the locale.""" locale = Locale.parse(locale) key = str(locale) rv = _translations.get(key) if rv is None: catalog = find_catalog(locale) if catalog is None: rv = NullTranslations() else: with open(catalog, 'rb') as f: rv = Translations(fileobj=f, domain=LOCALE_DOMAIN) _translations[key] = rv return rv
def _load_domain(self, domain, fallback=True): """Load the given domain from one of the pre-configured locale dirs. Returns a :class:`gettext.NullTranslations` instance if no translations could be found for a non-critical domain. This allows untranslated plugins to be rendered in English instead of an error being raised. :param domain: A domain name. :param fallback: An optional flag that, when True, returns a :class:`gettext.NullTranslations` instance if no translations file could be found for the given language(s). :rtype: :class:`gettext.GNUTranslations` :returns: The native python translator instance for this domain. :raises DomainError: If no locale dir has been configured for this domain and the fallback is off. :raises LanguageError: If no translations could be found for this domain in this locale and the fallback is off. """ locale_dirs = self._locale_dirs.get(domain, None) if locale_dirs: if isinstance(locale_dirs, basestring): locale_dirs = (locale_dirs, ) translation_list = self._load_translations(domain, locale_dirs, fallback) if (not fallback) and len(translation_list) == 0: msg = 'No %r translations found for %r in %r.' raise LanguageError(msg % (domain, self._languages, locale_dirs)) translations = Translations(domain=domain) for translation in translation_list: translations.merge(translation) elif fallback: translations = NullTranslations() else: raise DomainError('No localedir specified for domain %r' % domain) self._domains[domain] = translations return translations
def generate_translations(self): from StringIO import StringIO from babel.messages import Catalog, mofile, pofile from babel.support import Translations catalog = Catalog(locale='ko_KR') po = ''' # ugettext msgid "I like a {0}." msgstr "나는 {0:을} 좋아합니다.' # ungettext msgid "Here is a {0}." msgid_plural "Here are {1} {0}." msgstr[0] "여기 {0:이} 있습니다." msgstr[1] "여기 {0:이} {1}개 있습니다." # ugettext msgid "I reached level {0}." msgstr "나는 레벨{0:이} 되었습니다.' ''' buf = StringIO() catalog = pofile.read_po(StringIO(po)) mofile.write_mo(buf, catalog) buf.seek(0) return Translations(buf)
def load_translations(lang): po = os.path.join(root, lang, 'messages.po') mo_path = os.path.join(root, lang, 'messages.mo') if os.path.exists(mo_path): return Translations(open(mo_path, 'rb'))
from datetime import date, datetime, time, timedelta from functools import partial import json import operator import traceback from babel import Locale, dates, numbers from babel.support import Translations from decimal import Decimal import collections import jsonschema from pycroft.helpers.interval import (Interval, Bound, NegativeInfinity, PositiveInfinity) _unspecified_locale = Locale('en', 'US') _null_translations = Translations() _locale_lookup = lambda: _unspecified_locale _translations_lookup = lambda: _null_translations def get_locale(): return _locale_lookup() def get_translations(): return _translations_lookup() def set_locale_lookup(lookup_func): global _locale_lookup _locale_lookup = lookup_func
# Mail:[email protected] # Created Time: 2015-10-29 07:09:54 # ************************************************************************* from flask import session from wtforms import (StringField, PasswordField, BooleanField) from wtforms.validators import Length, DataRequired, Email from flask_maple.babel import lazy_gettext as _ try: from flask_wtf import FlaskForm as Form except ImportError: from flask_wtf import Form from babel.support import Translations translations = Translations() class BaseForm(Form): username = StringField( _('Username:'******'Password:'******'Captcha:'), [DataRequired(), Length(min=4, max=4)]) def validate(self): rv = Form.validate(self) if not rv: return False
LOCALE_DIR = __base_dir__.joinpath('locale') if not LOCALE_DIR.is_dir(): LOCALE_DIR = __module_dir__.joinpath('locale') if not LOCALE_DIR.is_dir(): LOCALE_DIR = None DEFAULT_LOCALE_DEF = 'en_US' DEFAULT_LOCALE = babel.core.default_locale() if not DEFAULT_LOCALE: DEFAULT_LOCALE = DEFAULT_LOCALE_DEF __mo_file__ = gettext.find(DOMAIN, str(LOCALE_DIR)) if __mo_file__: try: with open(__mo_file__, 'rb') as F: XLATOR = Translations(F, DOMAIN) except IOError: XLATOR = gettext.NullTranslations() else: XLATOR = gettext.NullTranslations() CUR_BABEL_VERSION = LooseVersion(babel.__version__) NEWER_BABEL_VERSION = LooseVersion('2.6.0') SUPPORTED_LANGS = ('de_DE', 'en_US') _ = XLATOR.gettext # ============================================================================= def format_list(lst, do_repr=False, style='standard', locale=DEFAULT_LOCALE):