Python babel.Locale() Examples

The following are 12 code examples of babel.Locale(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module babel , or try the search function .
Example #1
Source File: test_utils.py    From zou with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_serialize_value(self):
        now = datetime.datetime.now()
        self.assertEqual(
            now.replace(microsecond=0).isoformat(),
            fields.serialize_value(now)
        )
        unique_id = uuid.uuid4()
        self.assertEqual(str(unique_id), fields.serialize_value(unique_id))
        self.assertEqual(
            {"now": now.replace(microsecond=0).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"))
        ) 
Example #2
Source File: datetimetz.py    From zim-desktop-wiki with GNU General Public License v2.0 6 votes vote down vote up
def init_first_day_of_week():
	global FIRST_DAY_OF_WEEK
	try:
		import babel
		mylocale = babel.Locale(locale.getdefaultlocale()[0])
		if mylocale.first_week_day == 0:
			FIRST_DAY_OF_WEEK = MONDAY
		else:
			FIRST_DAY_OF_WEEK = SUNDAY
		logger.debug('According to babel first day of week is %i', FIRST_DAY_OF_WEEK)
	except Exception as e:
		if not isinstance(e, ImportError):
			logger.exception('Exception while loading \'babel\' library for first day of week')

		# Fallback gleaned from gtkcalendar.c - hence the inconsistency
		# with weekday numbers in iso calendar...
		t = _("calendar:week_start:0")
		# T: Translate to "calendar:week_start:0" if you want Sunday to be the first day of the week or to "calendar:week_start:1" if you want Monday to be the first day of the week
		if t[-1] == '0':
			FIRST_DAY_OF_WEEK = SUNDAY
		elif t[-1] == '1':
			FIRST_DAY_OF_WEEK = MONDAY
		else:
			logger.warn("Whoever translated 'calendar:week_start:0' did so wrongly.")
			FIRST_DAY_OF_WEEK = SUNDAY 
Example #3
Source File: view.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def babel_languages(self) -> List[Locale]:
        return APP.babel.list_translations() 
Example #4
Source File: admin.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def new_user():
    content = ub.User()
    languages = calibre_db.speaking_language()
    translations = [LC('en')] + babel.list_translations()
    kobo_support = feature_support['kobo'] and config.config_kobo_sync
    if request.method == "POST":
        to_save = request.form.to_dict()
        _handle_new_user(to_save, content, languages, translations, kobo_support)
    else:
        content.role = config.config_default_role
        content.sidebar_view = config.config_default_show
    return render_title_template("user_edit.html", new_user=1, content=content, translations=translations,
                                 languages=languages, title=_(u"Add new user"), page="newuser",
                                 kobo_support=kobo_support, registered_oauth=oauth_check) 
Example #5
Source File: admin.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def edit_user(user_id):
    content = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first()  # type: ub.User
    if not content:
        flash(_(u"User not found"), category="error")
        return redirect(url_for('admin.admin'))
    downloads = list()
    languages = calibre_db.speaking_language()
    translations = babel.list_translations() + [LC('en')]
    kobo_support = feature_support['kobo'] and config.config_kobo_sync
    for book in content.downloads:
        downloadbook = calibre_db.get_book(book.book_id)
        if downloadbook:
            downloads.append(downloadbook)
        else:
            ub.delete_download(book.book_id)
    if request.method == "POST":
        to_save = request.form.to_dict()
        _handle_edit_user(to_save, content, languages, translations, kobo_support, downloads)
    return render_title_template("user_edit.html",
                                 translations=translations,
                                 languages=languages,
                                 new_user=0,
                                 content=content,
                                 downloads=downloads,
                                 registered_oauth=oauth_check,
                                 mail_configured=config.get_mail_server_configured(),
                                 kobo_support=kobo_support,
                                 title=_(u"Edit User %(nick)s", nick=content.nickname), page="edituser") 
Example #6
Source File: commands.py    From critics with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #7
Source File: fields.py    From zou with GNU Affero General Public License v3.0 5 votes vote down vote up
def serialize_value(value):
    """
    Utility function to handle the normalizing of specific fields.
    The aim is to make the result JSON serializable
    """
    if isinstance(value, datetime.datetime):
        return value.replace(microsecond=0).isoformat()
    if isinstance(value, datetime.date):
        return value.isoformat()
    elif isinstance(value, uuid.UUID):
        return str(value)
    elif isinstance(value, dict):
        return serialize_dict(value)
    elif isinstance(value, orm.collections.InstrumentedList):
        return serialize_orm_arrays(value)
    elif isinstance(value, bytes):
        return value.decode("utf-8")
    elif isinstance(value, str):
        return value
    elif isinstance(value, int):
        return value
    elif isinstance(value, list):
        return serialize_list(value)
    elif isinstance(value, Locale):
        return str(value)
    elif isinstance(value, tzinfo.DstTzInfo):
        return str(value)
    elif isinstance(value, Choice):
        return value.code
    elif isinstance(value, IPv4Address):
        return str(value)
    elif value is None:
        return None
    elif isinstance(value, object):
        if hasattr(value, "serialize"):
            return value.serialize()
        else:
            return value
    else:
        return value 
Example #8
Source File: test_helpers.py    From daf-recipes with GNU General Public License v3.0 5 votes vote down vote up
def test_url_for_with_locale_object(self):
        url = '/foo/de/dataset/my_dataset'
        generated_url = h.url_for('/dataset/my_dataset',
                                  locale=Locale('de'))
        eq_(generated_url, url) 
Example #9
Source File: requests.py    From evesrp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def title(self):
        current_locale = get_locale()
        if current_locale is None:
            current_locale = babel.Locale('en')
        # Special case possesive form in English
        if current_locale.language.lower() == 'en' and \
                current_user.name[:-1] == u's':
            return u"{}' Requests".format(current_user.name)
        else:
            # TRANS: The title of the page listing all requests an individual
            # TRANS: user has made.
            return gettext(u"%(name)s's Requests", name=current_user.name) 
Example #10
Source File: preprocessors.py    From text-to-text-transfer-transformer with Apache License 2.0 5 votes vote down vote up
def translate(dataset, source_language, target_language):
  """Convert a translation dataset to a text2text pair.

  For example, say the dataset returns examples of this format:
    {'de': 'Das ist gut.', 'en': 'That is good.'}
  If source_language = 'de', target_language = 'en', then the outputs will have
  the format:
    {'inputs': 'translate German to English: Das ist gut.',
     'targets': 'That is good.'}

  Args:
    dataset: a tf.data.Dataset to process.
    source_language: source language code (e.g. 'en') to translate from.
    target_language: target language code (e.g. 'de') to translate to.

  Returns:
    A preprocessed tf.data.Dataset with the format listed above.
  """
  # Language codes like zh-cn are not supported; use only the first 2 chars
  for language in (source_language, target_language):
    if language != language[:2]:
      tf.logging.warn(
          'Extended language code {} not supported. Falling back on {}'.format(
              language, language[:2]
          )
      )
  lang_id_to_string = {
      source_language: babel.Locale(source_language[:2]).english_name,
      target_language: babel.Locale(target_language[:2]).english_name,
  }
  def my_fn(x):
    """Add translate X to X strings to source/target language strings."""
    src_str = 'translate {}'.format(lang_id_to_string[source_language])
    tgt_str = ' to {}: '.format(lang_id_to_string[target_language])
    return {
        'inputs': tf.strings.join([src_str, tgt_str, x[source_language]]),
        'targets': x[target_language],
    }
  return dataset.map(my_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE) 
Example #11
Source File: time.py    From fbchat-archive-parser with MIT License 5 votes vote down vote up
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())) 
Example #12
Source File: utils.py    From personfinder with Apache License 2.0 5 votes vote down vote up
def __get_env_language_for_babel(self):
        language_code = self.env.lang
        try:
            return babel.Locale.parse(language_code, sep='-')
        except babel.UnknownLocaleError as e:
            # fallback language
            return babel.Locale('en')