本文整理汇总了Python中babel.Locale.parse方法的典型用法代码示例。如果您正苦于以下问题:Python Locale.parse方法的具体用法?Python Locale.parse怎么用?Python Locale.parse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类babel.Locale
的用法示例。
在下文中一共展示了Locale.parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: language_overview
# 需要导入模块: from babel import Locale [as 别名]
# 或者: from babel.Locale import parse [as 别名]
def language_overview():
if current_user.check_visibility(constants.SIDEBAR_LANGUAGE):
charlist = list()
if current_user.filter_language() == u"all":
languages = calibre_db.speaking_language()
# ToDo: generate first character list for languages
else:
try:
cur_l = LC.parse(current_user.filter_language())
except UnknownLocaleError:
cur_l = None
languages = calibre_db.session.query(db.Languages).filter(
db.Languages.lang_code == current_user.filter_language()).all()
if cur_l:
languages[0].name = cur_l.get_language_name(get_locale())
else:
languages[0].name = _(isoLanguages.get(part3=languages[0].lang_code).name)
lang_counter = calibre_db.session.query(db.books_languages_link,
func.count('books_languages_link.book').label('bookcount')).group_by(
text('books_languages_link.lang_code')).all()
return render_title_template('languages.html', languages=languages, lang_counter=lang_counter,
charlist=charlist, title=_(u"Languages"), page="langlist",
data="language")
else:
abort(404)
示例2: get_locale
# 需要导入模块: from babel import Locale [as 别名]
# 或者: from babel.Locale import parse [as 别名]
def get_locale():
# if a user is logged in, use the locale from the user settings
user = getattr(g, 'user', None)
# user = None
if user is not None and hasattr(user, "locale"):
if user.nickname != 'Guest': # if the account is the guest account bypass the config lang settings
return user.locale
preferred = list()
if request.accept_languages:
for x in request.accept_languages.values():
try:
preferred.append(str(LC.parse(x.replace('-', '_'))))
except (UnknownLocaleError, ValueError) as e:
log.debug('Could not parse locale "%s": %s', x, e)
return negotiate_locale(preferred or ['en'], _BABEL_TRANSLATIONS)
示例3: speaking_language
# 需要导入模块: from babel import Locale [as 别名]
# 或者: from babel.Locale import parse [as 别名]
def speaking_language(self, languages=None):
from . import get_locale
if not languages:
languages = self.session.query(Languages) \
.join(books_languages_link) \
.join(Books) \
.filter(self.common_filters()) \
.group_by(text('books_languages_link.lang_code')).all()
for lang in languages:
try:
cur_l = LC.parse(lang.lang_code)
lang.name = cur_l.get_language_name(get_locale())
except UnknownLocaleError:
lang.name = _(isoLanguages.get(part3=lang.lang_code).name)
return languages
示例4: get_available_locales
# 需要导入模块: from babel import Locale [as 别名]
# 或者: from babel.Locale import parse [as 别名]
def get_available_locales():
''' Get a list of the available locales
e.g. [ Locale('en'), Locale('de'), ... ] '''
global available_locales
if not available_locales:
available_locales = []
for locale in get_locales():
# Add the short names for the locales. This equals the filename
# of the ckan translation files as opposed to the long name
# that includes the script which is generated by babel
# so e.g. `zn_CH` instead of `zn_Hans_CH` this is needed
# to properly construct urls with url_for
parsed_locale = Locale.parse(locale)
parsed_locale.short_name = locale
# Add the full identifier (eg `pt_BR`) to the locale classes,
# as it does not offer a way of accessing it directly
parsed_locale.identifier = \
get_identifier_from_locale_class(parsed_locale)
available_locales.append(parsed_locale)
return available_locales
示例5: get_locale
# 需要导入模块: from babel import Locale [as 别名]
# 或者: from babel.Locale import parse [as 别名]
def get_locale(locale_code):
locale = None
try:
locale = Locale.parse(locale_code)
except (UnknownLocaleError, ValueError) as e:
try:
locale = Locale.parse(locale_code, sep='-')
except (UnknownLocaleError, ValueError) as e:
pass
if locale_code in _cached_locale_:
locale = _cached_locale_[locale_code]
if locale:
_cached_locale_[locale_code] = locale
return locale
示例6: render_language_books
# 需要导入模块: from babel import Locale [as 别名]
# 或者: from babel.Locale import parse [as 别名]
def render_language_books(page, name, order):
try:
cur_l = LC.parse(name)
lang_name = cur_l.get_language_name(get_locale())
except UnknownLocaleError:
try:
lang_name = _(isoLanguages.get(part3=name).name)
except KeyError:
abort(404)
entries, random, pagination = calibre_db.fill_indexpage(page,
db.Books,
db.Books.languages.any(db.Languages.lang_code == name),
[db.Books.timestamp.desc(), order[0]])
return render_title_template('index.html', random=random, entries=entries, pagination=pagination, id=name,
title=_(u"Language: %(name)s", name=lang_name), page="language")
示例7: finalize_options
# 需要导入模块: from babel import Locale [as 别名]
# 或者: from babel.Locale import parse [as 别名]
def finalize_options(self):
if not self.input_file:
raise DistutilsOptionError('you must specify the input file')
if not self.locale:
raise DistutilsOptionError('you must provide a locale for the '
'new catalog')
try:
self._locale = Locale.parse(self.locale)
except UnknownLocaleError as e:
raise DistutilsOptionError(e)
if not self.output_file and not self.output_dir:
raise DistutilsOptionError('you must specify the output directory')
if not self.output_file:
self.output_file = os.path.join(self.output_dir, self.locale,
'LC_MESSAGES', self.domain + '.po')
if not os.path.exists(os.path.dirname(self.output_file)):
os.makedirs(os.path.dirname(self.output_file))
if self.no_wrap and self.width:
raise DistutilsOptionError("'--no-wrap' and '--width' are mutually "
"exclusive")
if not self.no_wrap and not self.width:
self.width = 76
elif self.width is not None:
self.width = int(self.width)
示例8: get_locales_dict
# 需要导入模块: from babel import Locale [as 别名]
# 或者: from babel.Locale import parse [as 别名]
def get_locales_dict():
''' Get a dict of the available locales
e.g. { 'en' : Locale('en'), 'de' : Locale('de'), ... } '''
global locales_dict
if not locales_dict:
locales = _get_locales()
locales_dict = {}
for locale in locales:
locales_dict[str(locale)] = Locale.parse(locale)
return locales_dict
示例9: get_locale
# 需要导入模块: from babel import Locale [as 别名]
# 或者: from babel.Locale import parse [as 别名]
def get_locale():
if 'locale' in session:
return Locale.parse(session.get('locale'))
else:
requested = request.accept_languages.values()
requested = [l.replace('-', '_') for l in requested]
available = map(unicode, babel.list_translations())
return Locale.negotiate(available, requested)
示例10: get_async_birthdays
# 需要导入模块: from babel import Locale [as 别名]
# 或者: from babel.Locale import parse [as 别名]
def get_async_birthdays(browser):
""" Returns list of birthday objects by querying the Facebook birthday async page """
FACEBOOK_BIRTHDAY_ASYNC_ENDPOINT = 'https://www.facebook.com/async/birthdays/?'
birthdays = []
next_12_months_epoch_timestamps = get_next_12_month_epoch_timestamps()
for epoch_timestamp in next_12_months_epoch_timestamps:
logger.info(f'Processing birthdays for month {datetime.fromtimestamp(epoch_timestamp).strftime("%B")}.')
# Not all fields are required for response to be given, required fields are date, fb_dtsg_ag and __a
query_params = {'date': epoch_timestamp,
'fb_dtsg_ag': get_async_token(browser),
'__a': '1'}
response = browser.get(FACEBOOK_BIRTHDAY_ASYNC_ENDPOINT + urllib.parse.urlencode(query_params))
if response.status_code != 200:
logger.debug(response.text)
logger.error(f'Failed to get async birthday response. Params: {query_params}. Status code: {response.status_code}.')
raise SystemError
birthdays_for_month = parse_birthday_async_output(browser, response.text)
birthdays.extend(birthdays_for_month)
logger.info(f'Found {len(birthdays_for_month)} birthdays for month {datetime.fromtimestamp(epoch_timestamp).strftime("%B")}.')
return birthdays
示例11: __init__
# 需要导入模块: from babel import Locale [as 别名]
# 或者: from babel.Locale import parse [as 别名]
def __init__(self, default_locale, translations):
if not isinstance(default_locale, Locale):
default_locale = Locale.parse(default_locale)
if default_locale.language not in translations:
raise KeyError('There are no translations for default locale %s' % default_locale)
self._default_locale = default_locale
self._translations = translations
示例12: _detect_locale
# 需要导入模块: from babel import Locale [as 别名]
# 或者: from babel.Locale import parse [as 别名]
def _detect_locale(self, request):
locale = _parse_accept_language(request.headers.get('accept-language'))
if locale:
try:
return Locale.parse(locale)
except Exception as exc:
logger.warning(
'Failed to parse locale: %s (locale=%r), '
'falling back to default',
exc,
locale
)
return self._default_locale
示例13: format_decimal
# 需要导入模块: from babel import Locale [as 别名]
# 或者: from babel.Locale import parse [as 别名]
def format_decimal(number, format=None, locale=LC_NUMERIC):
u"""Return the given decimal number formatted for a specific locale.
>>> format_decimal(1.2345, locale='en_US')
u'1.234'
>>> format_decimal(1.2346, locale='en_US')
u'1.235'
>>> format_decimal(-1.2346, locale='en_US')
u'-1.235'
>>> format_decimal(1.2345, locale='sv_SE')
u'1,234'
>>> format_decimal(1.2345, locale='de')
u'1,234'
The appropriate thousands grouping and the decimal separator are used for
each locale:
>>> format_decimal(12345.5, locale='en_US')
u'12,345.5'
:param number: the number to format
:param format:
:param locale: the `Locale` object or locale identifier
"""
locale = Locale.parse(locale)
if not format:
format = locale.decimal_formats.get(format)
pattern = parse_pattern(format)
return pattern.apply(number, locale)
示例14: show_book
# 需要导入模块: from babel import Locale [as 别名]
# 或者: from babel.Locale import parse [as 别名]
def show_book(book_id):
entries = calibre_db.get_filtered_book(book_id, allow_show_archived=True)
if entries:
for index in range(0, len(entries.languages)):
try:
entries.languages[index].language_name = LC.parse(entries.languages[index].lang_code)\
.get_language_name(get_locale())
except UnknownLocaleError:
entries.languages[index].language_name = _(
isoLanguages.get(part3=entries.languages[index].lang_code).name)
cc = get_cc_columns(filter_config_custom_read=True)
book_in_shelfs = []
shelfs = ub.session.query(ub.BookShelf).filter(ub.BookShelf.book_id == book_id).all()
for entry in shelfs:
book_in_shelfs.append(entry.shelf)
if not current_user.is_anonymous:
if not config.config_read_column:
matching_have_read_book = ub.session.query(ub.ReadBook). \
filter(and_(ub.ReadBook.user_id == int(current_user.id), ub.ReadBook.book_id == book_id)).all()
have_read = len(
matching_have_read_book) > 0 and matching_have_read_book[0].read_status == ub.ReadBook.STATUS_FINISHED
else:
try:
matching_have_read_book = getattr(entries, 'custom_column_' + str(config.config_read_column))
have_read = len(matching_have_read_book) > 0 and matching_have_read_book[0].value
except (KeyError, AttributeError):
log.error("Custom Column No.%d is not existing in calibre database", config.config_read_column)
have_read = None
archived_book = ub.session.query(ub.ArchivedBook).\
filter(and_(ub.ArchivedBook.user_id == int(current_user.id),
ub.ArchivedBook.book_id == book_id)).first()
is_archived = archived_book and archived_book.is_archived
else:
have_read = None
is_archived = None
entries.tags = sort(entries.tags, key=lambda tag: tag.name)
entries = calibre_db.order_authors(entries)
kindle_list = check_send_to_kindle(entries)
reader_list = check_read_formats(entries)
audioentries = []
for media_format in entries.data:
if media_format.format.lower() in constants.EXTENSIONS_AUDIO:
audioentries.append(media_format.format.lower())
return render_title_template('detail.html', entry=entries, audioentries=audioentries, cc=cc,
is_xhr=request.headers.get('X-Requested-With')=='XMLHttpRequest', title=entries.title, books_shelfs=book_in_shelfs,
have_read=have_read, is_archived=is_archived, kindle_list=kindle_list, reader_list=reader_list, page="book")
else:
log.debug(u"Error opening eBook. File does not exist or file is not accessible")
flash(_(u"Error opening eBook. File does not exist or file is not accessible"), category="error")
return redirect(url_for("web.index"))
示例15: run
# 需要导入模块: from babel import Locale [as 别名]
# 或者: from babel.Locale import parse [as 别名]
def run(self, argv=sys.argv):
"""Main entry point of the command-line interface.
:param argv: list of arguments passed on the command-line
"""
self.parser = OptionParser(usage=self.usage % ('command', '[args]'),
version=self.version)
self.parser.disable_interspersed_args()
self.parser.print_help = self._help
self.parser.add_option('--list-locales', dest='list_locales',
action='store_true',
help="print all known locales and exit")
self.parser.add_option('-v', '--verbose', action='store_const',
dest='loglevel', const=logging.DEBUG,
help='print as much as possible')
self.parser.add_option('-q', '--quiet', action='store_const',
dest='loglevel', const=logging.ERROR,
help='print as little as possible')
self.parser.set_defaults(list_locales=False, loglevel=logging.INFO)
options, args = self.parser.parse_args(argv[1:])
self._configure_logging(options.loglevel)
if options.list_locales:
identifiers = localedata.locale_identifiers()
longest = max([len(identifier) for identifier in identifiers])
identifiers.sort()
format = u'%%-%ds %%s' % (longest + 1)
for identifier in identifiers:
locale = Locale.parse(identifier)
output = format % (identifier, locale.english_name)
print(output.encode(sys.stdout.encoding or
getpreferredencoding() or
'ascii', 'replace'))
return 0
if not args:
self.parser.error('no valid command or option passed. '
'Try the -h/--help option for more information.')
cmdname = args[0]
if cmdname not in self.commands:
self.parser.error('unknown command "%s"' % cmdname)
return getattr(self, cmdname)(args[1:])