本文整理匯總了Python中babel.Locale方法的典型用法代碼示例。如果您正苦於以下問題:Python babel.Locale方法的具體用法?Python babel.Locale怎麽用?Python babel.Locale使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類babel
的用法示例。
在下文中一共展示了babel.Locale方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_serialize_value
# 需要導入模塊: import babel [as 別名]
# 或者: from babel import Locale [as 別名]
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"))
)
示例2: init_first_day_of_week
# 需要導入模塊: import babel [as 別名]
# 或者: from babel import Locale [as 別名]
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
示例3: babel_languages
# 需要導入模塊: import babel [as 別名]
# 或者: from babel import Locale [as 別名]
def babel_languages(self) -> List[Locale]:
return APP.babel.list_translations()
示例4: new_user
# 需要導入模塊: import babel [as 別名]
# 或者: from babel import Locale [as 別名]
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)
示例5: edit_user
# 需要導入模塊: import babel [as 別名]
# 或者: from babel import Locale [as 別名]
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")
示例6: setup_languages
# 需要導入模塊: import babel [as 別名]
# 或者: from babel import Locale [as 別名]
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
示例7: serialize_value
# 需要導入模塊: import babel [as 別名]
# 或者: from babel import Locale [as 別名]
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
示例8: test_url_for_with_locale_object
# 需要導入模塊: import babel [as 別名]
# 或者: from babel import Locale [as 別名]
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)
示例9: title
# 需要導入模塊: import babel [as 別名]
# 或者: from babel import Locale [as 別名]
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)
示例10: translate
# 需要導入模塊: import babel [as 別名]
# 或者: from babel import Locale [as 別名]
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)
示例11: __init__
# 需要導入模塊: import babel [as 別名]
# 或者: from babel import Locale [as 別名]
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()))
示例12: __get_env_language_for_babel
# 需要導入模塊: import babel [as 別名]
# 或者: from babel import Locale [as 別名]
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')