def __init__(self, request): self.request = request self._ = self.request.translate self.resultDict = {} self.errors = [] self.justReturn = False locale = Locale(request.locale_name) if locale.character_order == "left-to-right": self.resultDict["rtl"] = False else: self.resultDict["rtl"] = True
def test_serialize_value(self): now = datetime.datetime.now() self.assertEqual(now.isoformat(), fields.serialize_value(now)) unique_id = uuid.uuid4() self.assertEqual(str(unique_id), fields.serialize_value(unique_id)) self.assertEqual({"now": now.isoformat()}, fields.serialize_value({"now": now})) self.assertEqual("Europe/Paris", fields.serialize_value(timezone("Europe/Paris"))) self.assertEqual("Europe/Brussels", fields.serialize_value(timezone("Europe/Brussels"))) self.assertEqual("en_US", fields.serialize_value(Locale("en_US")))
def set_defaults(self, default_locale, default_timezone): """Set the default locale from the configuration as an instance of :class:`babel.core.Locale` and the default timezone as a `datetime.tzinfo`. """ self.default_locale = utils.normalize_locale(default_locale) or Locale( DEFAULT_LOCALE ) self.default_timezone = utils.normalize_timezone( default_timezone ) or get_timezone(DEFAULT_TIMEZONE)
def metadata(): """Get operational metadata for the frontend. --- get: summary: Retrieve system metadata from the application. responses: '200': description: OK content: application/json: schema: type: object tags: - System """ locale = get_locale() enable_cache(vary_user=False, vary=str(locale)) key = cache.key('metadata', settings.PROCESS_ID, locale) data = cache.get_complex(key) if data is not None: return jsonify(data) auth = {} if settings.PASSWORD_LOGIN: auth['password_login_uri'] = url_for('sessions_api.password_login') auth['registration_uri'] = url_for('roles_api.create_code') if settings.OAUTH: auth['oauth_uri'] = url_for('sessions_api.oauth_init') locales = settings.UI_LANGUAGES locales = {l: Locale(l).get_language_name(l) for l in locales} data = { 'status': 'ok', 'maintenance': request.authz.in_maintenance, 'app': { 'title': settings.APP_TITLE, 'description': settings.APP_DESCRIPTION, 'version': __version__, 'banner': settings.APP_BANNER, 'ui_uri': settings.APP_UI_URL, 'samples': settings.SAMPLE_SEARCHES, 'logo': settings.APP_LOGO, 'favicon': settings.APP_FAVICON, 'locale': str(locale), 'locales': locales }, 'categories': Collection.CATEGORIES, 'model': model, 'auth': auth } cache.set_complex(key, data, expires=120) return jsonify(data)
def __init__(self, initial=None): choices = [('', '---------')] locale = Locale(translation.get_language()) for prefix, values in _COUNTRY_CODE_TO_REGION_CODE.iteritems(): prefix = '+%d' % prefix if initial and initial in values: self.initial = prefix for country_code in values: country_name = locale.territories.get(country_code) if country_name: choices.append((prefix, u'%s %s' % (country_name, prefix))) return super(PhonePrefixSelect, self).__init__(choices=sorted(choices, key=lambda item: item[1]))
def install_locale(cls, locale_code, locale_type): """Install the locale specified by `language_code`, for localizations of type `locale_type`. If we can't perform localized formatting for the specified locale, then the default localization format will be used. If the locale specified is already installed for the selected type, then this is a no-op. """ # Skip if the locale is already installed if locale_code == getattr(cls, locale_type): return try: # We create a Locale instance to see if the locale code is supported locale = Locale(locale_code) log.debug('Installed locale %s', locale_code) except UnknownLocaleError: default = settings.DEFAULT_LOCALIZATION_FORMAT log.warning('Unknown locale %s, falling back to %s', locale_code, default) locale = Locale(default) setattr(cls, locale_type, locale.language)
def test_translate_sets_language(): catalog = Catalog(locale=Locale("cy")) catalog.add("test") schema_translation = SchemaTranslation(catalog=catalog) schema = SurveySchema({}) schema.translate(schema_translation) translated_schema = schema.translate(schema_translation) assert translated_schema.language == "cy"
def metadata(): """Get operational metadata for the frontend. --- get: summary: Retrieve system metadata from the application. responses: '200': description: OK content: application/json: schema: type: object tags: - System """ locale = get_locale() auth = {} if settings.PASSWORD_LOGIN: auth['password_login_uri'] = url_for('sessions_api.password_login') auth['registration_uri'] = url_for('roles_api.create_code') if settings.OAUTH: auth['oauth_uri'] = url_for('sessions_api.oauth_init') locales = settings.UI_LANGUAGES locales = {l: Locale(l).get_language_name(l) for l in locales} data = { 'status': 'ok', 'maintenance': request.authz.in_maintenance, 'app': { 'title': settings.APP_TITLE, 'description': settings.APP_DESCRIPTION, 'version': __version__, 'banner': settings.APP_BANNER, 'ui_uri': settings.APP_UI_URL, 'samples': settings.SAMPLE_SEARCHES, 'logo': settings.APP_LOGO, 'favicon': settings.APP_FAVICON, 'locale': str(locale), 'locales': locales }, 'categories': Collection.CATEGORIES, 'model': model, 'token': None, 'auth': auth } if settings.SINGLE_USER: role = Role.load_cli_user() authz = Authz.from_role(role) data['token'] = authz.to_token(role=role) return jsonify(data)
def _format_decimal(num, format=None): """Returns the string of a number formatted for the current language. Uses django's translation.get_language() to find the current language from the request. Falls back to the default language if babel does not support the current. """ lang = translation.get_language() if not localedata.exists(lang): lang = settings.LANGUAGE_CODE locale = Locale(translation.to_locale(lang)) return Format(locale).decimal(num, format)
async def choose_locale(message: types.Message): """Show list of languages.""" keyboard = InlineKeyboardMarkup() for language in i18n.available_locales: keyboard.row( InlineKeyboardButton( Locale(language).display_name, callback_data="locale {}".format(language), ) ) await tg.send_message( message.chat.id, i18n("choose_your_language"), reply_markup=keyboard )
def get_locale_english_name(lang, country): """ Retrieves a string representation of a Locale. @param lang: Lang code. @param country: Country code. @return: String representation for the locale. """ if lang == 'mk': return u"Macedonian Slavic" if lang == 'zh': if country in ('CN', 'ALL'): return u'Chinese (Simplified)' elif country == 'TW': return u'Chinese (Traditional)' try: if country.upper() == 'ALL': country = "" return Locale(lang, country).english_name except UnknownLocaleError: return Locale("en", "US").languages.get(lang)
def test_get_translations_from_locale(): i18n = I18n(LOCALES_TEST) ltrans_es = i18n.get_translations_from_locale(Locale('es')) assert len(ltrans_es) == 1 expected_es = 'foo cat greeting accented so'.split() trans_es = ltrans_es[0] assert sorted(trans_es.keys()) == sorted(expected_es) ltrans_espe = i18n.get_translations_from_locale(Locale('es', 'PE')) assert len(ltrans_espe) == 2 expected_es = 'foo cat greeting accented so'.split() expected_espe = 'greeting'.split() trans_espe = ltrans_espe[0] trans_es = ltrans_espe[1] assert sorted(trans_espe.keys()) == sorted(expected_espe) assert sorted(trans_es.keys()) == sorted(expected_es) ltrans_en = i18n.get_translations_from_locale(Locale('en')) expected_en = 'foo cat greeting apple with_html sub1'.split() trans_en = ltrans_en[0] assert sorted(trans_en.keys()) == sorted(expected_en)
def test_format_interval(self): tz = tzlocal() locale = Locale('fi') d0 = datetime(2016, 4, 27, 21, 0, 0, tzinfo=tz) d1 = datetime(2016, 4, 27, 23, 0, 0, tzinfo=tz) d2 = datetime(2016, 4, 28, 1, 0, 0, tzinfo=tz) self.assertEqual(format_interval(d0, d1, locale=locale), 'ke 27.4. klo 21.00–23.00') self.assertEqual(format_interval(d0, d2, locale=locale), 'ke 27.4. klo 21.00 – to 28.4. klo 1.00')
def marc21_to_languages(self, key, value): """Get languages. languages: 008 and 041 [$a, repetitive] """ language = value.strip()[35:38] code = current_app.config.get('SONAR_APP_LANGUAGES_MAP')[language] to_return = [{ 'code': language, 'name': Locale(code).get_language_name().capitalize() }] return to_return
def __init__(self, initial=None): choices = [("", "---------")] language = get_babel_locale() # changed from default implementation that used the django locale locale = Locale(translation.to_locale(language)) for prefix, values in _COUNTRY_CODE_TO_REGION_CODE.items(): prefix = "+%d" % prefix if initial and initial in values: self.initial = prefix for country_code in values: country_name = locale.territories.get(country_code) if country_name: choices.append((prefix, "{} {}".format(country_name, prefix))) super().__init__(choices=sorted(choices, key=lambda item: item[1]), attrs={'aria-label': pgettext_lazy('phonenumber', 'International area code')})
class Person(db.Model, BaseMixin, SerializerMixin): """ Describe a member of the studio (and an API user). """ first_name = db.Column(db.String(80), nullable=False) last_name = db.Column(db.String(80), nullable=False) email = db.Column(EmailType, unique=True) phone = db.Column(db.String(30)) active = db.Column(db.Boolean(), default=True) last_presence = db.Column(db.Date()) password = db.Column(db.Binary(60)) desktop_login = db.Column(db.String(80)) shotgun_id = db.Column(db.Integer, unique=True) timezone = db.Column( TimezoneType(backend="pytz"), default=pytz_timezone("Europe/Paris") ) locale = db.Column(LocaleType, default=Locale("en", "US")) data = db.Column(JSONB) role = db.Column(db.String(30), default="user") has_avatar = db.Column(db.Boolean(), default=False) skills = db.relationship( "Department", secondary=department_link ) def __repr__(self): if sys.version_info[0] < 3: return "<Person %s>" % self.full_name().encode("utf-8") else: return "<Person %s>" % self.full_name() def full_name(self): return "%s %s" % ( self.first_name, self.last_name ) def serialize(self, obj_type="Person"): data = SerializerMixin.serialize(self, "Person") data["full_name"] = self.full_name() return data def serialize_safe(self): data = SerializerMixin.serialize(self, "Person") data["full_name"] = self.full_name() del data["password"] return data
def test_key_lookup(): i18n = I18n(LOCALES_TEST) locale = Locale('es') assert i18n.key_lookup(locale, 'greeting') == u'Hola mundo' assert i18n.key_lookup(locale, 'so.much.such') == u'wow' locale = Locale('es', 'PE') assert i18n.key_lookup(locale, 'greeting') == u'Habla' locale = Locale('en') expected = { 'zero': 'No apples', 'one': 'One apple', 'many': '{count} apples', } assert i18n.key_lookup(locale, 'apple') == expected # Key not found assert i18n.key_lookup(locale, 'this.is.wrong') is None # Language not found assert i18n.key_lookup(Locale('fr'), 'greeting') is None
def getLocaleContainer(cls): localeContainer = IndexedContainer() localeContainer.addContainerProperty(cls.locale_PROPERTY_LOCALE, Locale, None) localeContainer.addContainerProperty(cls.locale_PROPERTY_NAME, str, None) for i in range(len(cls._locales)): idd = cls._locales[i][2] item = localeContainer.addItem(idd) v = Locale(cls._locales[i][0], cls._locales[i][1]) item.getItemProperty(cls.locale_PROPERTY_LOCALE).setValue(v) v = cls._locales[i][2] item.getItemProperty(cls.locale_PROPERTY_NAME).setValue(v) return localeContainer
def get_country_name_by_code(code, default=None): """Return a country name string from a country code. Args: code (str): country code in INSPIRE 2 letter format based on ISO 3166-1 alpha-2 default: value to be returned if no country of a given code exists Returns: text_type: name of a country, or ``default`` if no such country. """ try: return Locale('en').territories[code] except KeyError: return default
def __init__(self, default_data=False, enable=None): """Construct a new Environment stub object. :param default_data: If True, populate the database with some defaults. :param enable: A list of component classes or name globs to activate in the stub environment. """ ComponentManager.__init__(self) Component.__init__(self) self.systeminfo = [] import trac self.path = os.path.dirname(trac.__file__) if not os.path.isabs(self.path): self.path = os.path.join(os.getcwd(), self.path) # -- configuration self.config = Configuration(None) # We have to have a ticket-workflow config for ''lots'' of things to # work. So insert the basic-workflow config here. There may be a # better solution than this. load_workflow_config_snippet(self.config, 'basic-workflow.ini') self.config.set('logging', 'log_level', 'DEBUG') self.config.set('logging', 'log_type', 'stderr') if enable is not None: self.config.set('components', 'trac.*', 'disabled') for name_or_class in enable or (): config_key = self._component_name(name_or_class) self.config.set('components', config_key, 'enabled') # -- logging from trac.log import logger_handler_factory self.log, self._log_handler = logger_handler_factory('test') # -- database self.dburi = get_dburi() if self.dburi.startswith('sqlite'): self.config.set('trac', 'database', 'sqlite::memory:') self.db = InMemoryDatabase() if default_data: self.reset_db(default_data) from trac.web.href import Href self.href = Href('/trac.cgi') self.abs_href = Href('http://example.org/trac.cgi') self.known_users = [] translation.activate(Locale and Locale('en', 'US'))
def _price(self): """Return the price and currency for the current locale.""" if not hasattr(self, '_currencies'): Price.transformer([]) lang = translation.get_language() locale = Locale(translation.to_locale(lang)) currency = amo.LOCALE_CURRENCY.get(locale.language) if currency: price_currency = Price._currencies.get((currency, self.id), None) if price_currency: return price_currency.price, currency, locale return self.price, self.currency, locale
def test_translate(language_struct, nonlanguage_struct): assert l10n.translate({}, 'en-US') == {} assert l10n.translate(42, 'fr') == 42 assert l10n.translate(None, 'de') is None assert l10n.translate(['list item'], Locale('en')) == ['list item'] assert l10n.translate({'nested dict': { 'en': 1, 'fr': 2 }}, 'en') == { 'nested dict': { 'en': 1, 'fr': 2 } } # noqa assert l10n.translate(nonlanguage_struct, 'fr') == nonlanguage_struct assert l10n.translate(nonlanguage_struct, 'fla') == 'non-language key' assert l10n.translate(language_struct, 'en') == 'English' assert l10n.translate(language_struct, 'en-US') == 'English (United States)' # noqa assert l10n.translate(language_struct, 'sq_AL') == Locale.parse('alb').display_name # noqa assert l10n.translate(language_struct, 'fr_CH') == Locale.parse('fr').display_name # noqa assert l10n.translate(language_struct, 'nl') == Locale.parse('nl_BE').display_name # noqa assert l10n.translate(language_struct, 'de') == 'English' assert l10n.translate(language_struct, Locale('en')) == 'English' assert l10n.translate( language_struct, Locale.parse('en_US')) == 'English (United States)' # noqa with pytest.raises(l10n.LocaleError): l10n.translate(language_struct, None) # noqa l10n.translate(language_struct, 42) # noqa
def test_one_plural_mode(): d = { 'one': u'one', 'two': u'two', 'few': u'few', 'many': u'many', 'other': u'other', } locale = Locale('zh') assert pluralize(d, 0, locale) == u'other' assert pluralize(d, 1, locale) == u'other' assert pluralize(d, 2, locale) == u'other' assert pluralize(d, 3, locale) == u'other' assert pluralize(d, 4, locale) == u'other' assert pluralize(d, 5, locale) == u'other' assert pluralize(d, 6, locale) == u'other' assert pluralize(d, 7, locale) == u'other' assert pluralize(d, 10, locale) == u'other' assert pluralize(d, 11, locale) == u'other' assert pluralize(d, 50, locale) == u'other' assert pluralize(d, 99, locale) == u'other' assert pluralize(d, 101, locale) == u'other' assert pluralize(d, 102, locale) == u'other' assert pluralize(d, 105, locale) == u'other' d = { 'zero': u'zero', 'one': u'one', 'two': u'two', 'few': u'few', 'many': u'many', 'other': u'other', } locale = Locale('zh') assert pluralize(d, 0, locale) == u'zero'
def setup_languages(settings): if not settings['language']: settings['language'] = [get_locale()[:2]] languages = [] language_names = [] for lang_code in settings['language']: try: language_names.append(Locale(lang_code).english_name) languages.append(lang_code) except UnknownLocaleError: raise click.ClickException('Unknown language code: %s' % lang_code) logger.info('Languages: %s', ', '.join(language_names)) return settings
def __init__(self, initial=None): choices = [("", "---------")] language = translation.get_language() or settings.LANGUAGE_CODE if language: locale = Locale(translation.to_locale(language)) for prefix, values in _COUNTRY_CODE_TO_REGION_CODE.items(): prefix = "+%d" % prefix if initial and initial in values: self.initial = prefix for country_code in values: country_name = locale.territories.get(country_code) if country_name: choices.append( (prefix, "{} {}".format(country_name, prefix))) super().__init__(choices=sorted(choices, key=lambda item: item[1]))
def localize_timestamp(timestamp, user): try: user_timezone = dates.get_timezone(user.timezone) except LookupError: user_timezone = dates.get_timezone('Etc/UTC') try: user_locale = Locale(user.locale) except core.UnknownLocaleError: user_locale = 'en' formatted_date = dates.format_date(timestamp, format='full', locale=user_locale) formatted_time = dates.format_time(timestamp, format='short', tzinfo=user_timezone, locale=user_locale) return u'{time} on {date}'.format(time=formatted_time, date=formatted_date)
def get_country_dict(): country_dict = {} for country in pycountry.countries: info = ln.get_territory_language_info(country.alpha_2) country_dict[country.name.lower()] = country.name.lower() if hasattr(country, "official_name"): country_dict[country.official_name.lower()] = country.name.lower() for lang in info.keys(): try: locale = Locale(lang, country.alpha_2) country_dict[locale.territories[country.alpha_2].lower()] = country.name.lower() except: pass country_dict["USA".lower()] = "United States of America".lower() return country_dict
def __init__(self, locale_id, timestamp_format, hints=None): self.locale_id = locale_id self.use_fallback = False self.original_timestamp_format = timestamp_format self.timestamp_format = timestamp_format.replace('dddd', 'd').replace('MMMM', 'M') locale = Locale(locale_id.split('_')[0]) self.translation_map = {k: str(v) for k, v in hints.items()} if hints else {} # Add in the month and day name data. for attr, start, end, offset in (('months', 1, 12, 0), ('days', 0, 6, 1)): for i in range(start, end + 1): attr_name = getattr(locale, attr)['format']['wide'][i] self.translation_map[attr_name.title()] = str(i + offset) self.translation_map[attr_name.lower()] = str(i + offset) self.matcher = re.compile('|'.join(self.translation_map.keys()))
def init_app(self, app): super(PopongBabel, self).init_app(app) self.localeselector(localeselector) # shortcuts app.babel = self app.LOCALES = self.list_translations() + [Locale('en')] # jinja filters app.jinja_env.filters['translit'] = filter_translit app.jinja_env.globals.update(translit=filter_translit) # context processor app.context_processor(inject_locales)
def parse_date(self, date): """Parse a date coming from Excel. :param date: cell value :returns: datetime.date """ if isinstance(date, basestring): d, m, y = date.split('-') d = int(d) mapping = Locale('en').months['format']['abbreviated'] mapping = dict(zip(mapping.values(), mapping.keys())) m = mapping[m] y = 2000 + int(y) return datetime.datetime(y, m, d) else: return datetime.datetime(*xldate_as_tuple(date, self.wb.datemode))