• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python babel.Locale类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中babel.Locale的典型用法代码示例。如果您正苦于以下问题:Python Locale类的具体用法?Python Locale怎么用?Python Locale使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Locale类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_i18n_parse_date_datetime_meridiem

        def test_i18n_parse_date_datetime_meridiem(self):
            tz = datefmt.timezone('GMT +2:00')
            expected_am = datetime.datetime(2011, 2, 22, 0, 45, 56, 0, tz)
            expected_pm = datetime.datetime(2011, 2, 22, 12, 45, 56, 0, tz)
            en_US = Locale.parse('en_US')
            zh_CN = Locale.parse('zh_CN')

            self.assertEqual(expected_am,
                             datefmt.parse_date('Feb 22, 2011 0:45:56 AM', tz,
                                                en_US))
            self.assertEqual(expected_am,
                             datefmt.parse_date('Feb 22, 2011 12:45:56 AM', tz,
                                                en_US))
            self.assertEqual(expected_am,
                             datefmt.parse_date(u'2011-2-22 上午0:45:56', tz,
                                                zh_CN))
            self.assertEqual(expected_am,
                             datefmt.parse_date(u'2011-2-22 上午12:45:56', tz,
                                                zh_CN))

            self.assertEqual(expected_pm,
                             datefmt.parse_date('Feb 22, 2011 0:45:56 PM', tz,
                                                en_US))
            self.assertEqual(expected_pm,
                             datefmt.parse_date('Feb 22, 2011 12:45:56 PM', tz,
                                                en_US))
            self.assertEqual(expected_pm,
                             datefmt.parse_date(u'2011-2-22 下午0:45:56', tz,
                                                zh_CN))
            self.assertEqual(expected_pm,
                             datefmt.parse_date(u'2011-2-22 下午12:45:56', tz,
                                                zh_CN))
开发者ID:trac-ja,项目名称:trac-ja,代码行数:32,代码来源:datefmt.py


示例2: handle_request

def handle_request(request, tmpl_context):
    from pylons import session

    tmpl_context.language = locale = None
    if 'locale' in session:
        locale = Locale.parse(session.get('locale'))
    else:
        requested = [l.replace('-', '_') for l in request.languages]
        locale = Locale.parse(Locale.negotiate(get_available_languages(), requested))

    if locale is None:
        locale = get_default_locale()

    tmpl_context.locale = locale

    options = [str(locale), locale.language, str(get_default_locale()),
        get_default_locale().language]
    for language in options:
        try:
            set_lang(language)
            # Lose the territory part of the locale string
            tmpl_context.language = get_lang()[0].split('_')[0]
            break
        except:
            pass
开发者ID:RandyMoore,项目名称:openspending,代码行数:25,代码来源:__init__.py


示例3: test_negotiate

 def test_negotiate(self):
     de_DE = Locale.negotiate(["de_DE", "en_US"], ["de_DE", "de_AT"])
     assert (de_DE.language, de_DE.territory) == ("de", "DE")
     de = Locale.negotiate(["de_DE", "en_US"], ["en", "de"])
     assert (de.language, de.territory) == ("de", None)
     nothing = Locale.negotiate(["de_DE", "de"], ["en_US"])
     assert nothing is None
开发者ID:nickretallack,项目名称:babel,代码行数:7,代码来源:test_core.py


示例4: user_language

def user_language(user, fallbacks=[]):
    # find out the locale
    locale = None
    if user and user.locale:
        locale = user.locale

    if locale is None:
        locales = map(str, LOCALES)
        locale = Locale.parse(Locale.negotiate(fallbacks, locales)) \
                 or get_default_locale()

    # determinate from which path we load the translations
    translations_module = config.get('adhocracy.translations', 'adhocracy')
    translations_module_loader = pkgutil.get_loader(translations_module)
    if translations_module_loader is None:
        raise ValueError(('Cannot import the module "%s" configured for '
                          '"adhocracy.translations". Make sure it is an '
                          'importable module (and contains the '
                          'translation files in a subdirectory '
                          '"i18n"') % translations_module)

    translations_root = translations_module_loader.filename
    translations_config = {'pylons.paths': {'root': translations_root},
                           'pylons.package': config.get('pylons.package')}

    # set language and fallback
    set_lang(locale.language, pylons_config=translations_config)
    add_fallback(get_default_locale().language,
                 pylons_config=translations_config)
    formencode.api.set_stdtranslation(domain="FormEncode",
                                      languages=[locale.language])
    return locale
开发者ID:JonnyWalker,项目名称:adhocracy,代码行数:32,代码来源:__init__.py


示例5: list_translations

    def list_translations(self):
        """Returns a list of all the locales translations exist for.  The
        list returned will be filled with actual locale objects and not just
        strings.

        .. versionadded:: 0.6
        """
        result = []

        for dirname in self.translation_directories:
            if not os.path.isdir(dirname):
                continue

            for folder in os.listdir(dirname):
                locale_dir = os.path.join(dirname, folder, 'LC_MESSAGES')
                if not os.path.isdir(locale_dir):
                    continue

                if filter(lambda x: x.endswith('.mo'), os.listdir(locale_dir)):
                    result.append(Locale.parse(folder))

        # If not other translations are found, add the default locale.
        if not result:
            result.append(Locale.parse(self._default_locale))

        return result
开发者ID:BryanSWong,项目名称:microblog,代码行数:26,代码来源:__init__.py


示例6: _set_language_dropdown_values

    def _set_language_dropdown_values(self, initial_locale=None):
        log.debug('Setting languages dropdown menu for %r' % initial_locale)
        available_locales = self._find_available_locales()
        locale = Locale(initial_locale)
        if not locale:
            locale = Locale.parse(initial_locale)
        languages = []
        current_lang = h.get_lang()[0]
        for loc in available_locales:
            selected = False
            if loc == current_lang:
                selected = True

            local_locale = Locale(loc)
            if not local_locale:
                local_locale = Locale.parse(loc)
            languages.append((loc, local_locale.get_display_name(locale), selected))
        return locale, languages

        for loc, territory in available_locales:
            selected = False
            language = locale.languages[loc].capitalize()
            if territory:
                country = u'(%s)' % locale.territories[territory]
                value = ['%s_%s' % (loc, territory),
                         u'%s %s' % (language, country)]
                if value[0] == current_lang:
                    selected = True
            else:
                value = [loc, language]
                if value[0] == current_lang:
                    selected = True
            languages.append( value + [selected])
        return locale, languages
开发者ID:UfSoft,项目名称:oil,代码行数:34,代码来源:base.py


示例7: __call__

 def __call__(self, value):
     normalized_value = value.replace(u"-", u"_")
     try:
         BabelLocale.parse(normalized_value)
         return normalized_value
     except (ValueError, UnknownLocaleError):
         raise ValidateError(_(u"Incorrect locale {}"), value)
开发者ID:deti,项目名称:boss,代码行数:7,代码来源:validator.py


示例8: negotiate_known_locale

 def negotiate_known_locale(self, preferred_locales):
     """Given a list of preferred locales, this method returns the best
     match locale object from the known ones."""
     assert isinstance(preferred_locales, (tuple, list))
     preferred_locales = [str(l).replace("-", "_") for l in preferred_locales]
     return Locale.parse(
         Locale.negotiate(preferred_locales, self.get_available_locale_names(), aliases=self.get_aliases())
     )
开发者ID:jasonzou,项目名称:ckan,代码行数:8,代码来源:i18n.py


示例9: get_locale

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)
开发者ID:CivicVision,项目名称:datahub,代码行数:8,代码来源:context.py


示例10: test_parse_likely_subtags

    def test_parse_likely_subtags(self):
        l = Locale.parse('zh-TW', sep='-')
        assert l.language == 'zh'
        assert l.territory == 'TW'
        assert l.script == 'Hant'

        l = Locale.parse('und_AT')
        assert l.language == 'de'
        assert l.territory == 'AT'
开发者ID:gjo,项目名称:babel,代码行数:9,代码来源:test_core.py


示例11: check_locale

 def check_locale(locale):
     if locale:
         try:
             Locale.parse(locale)
         except ValueError:
             return None
         else:
             return locale
     return None
开发者ID:Kiolali,项目名称:weblabdeusto,代码行数:9,代码来源:i18n.py


示例12: _get_locales

def _get_locales():
    # FIXME this wants cleaning up and merging with get_locales_from_config()
    assert not config.get('lang'), \
        ('"lang" config option not supported - please use ckan.locale_default '
         'instead.')
    locales_offered = config.get('ckan.locales_offered', '').split()
    filtered_out = config.get('ckan.locales_filtered_out', '').split()
    locale_default = config.get('ckan.locale_default', 'en')
    locale_order = config.get('ckan.locale_order', '').split()

    locales = ['en']
    if config.get('ckan.i18n_directory'):
        i18n_path = os.path.join(config.get('ckan.i18n_directory'), 'i18n')
    else:
        i18n_path = os.path.dirname(ckan.i18n.__file__)

    # For every file in the ckan i18n directory see if babel can understand
    # the locale. If yes, add it to the available locales
    for locale in os.listdir(i18n_path):
        try:
            Locale.parse(locale)
            locales.append(locale)
        except (ValueError, UnknownLocaleError):
            # Babel does not know how to make a locale out of this.
            # This is fine since we are passing all files in the
            # ckan.i18n_directory here which e.g. includes the __init__.py
            pass

    assert locale_default in locales, \
        'default language "%s" not available' % locale_default

    locale_list = []
    for locale in locales:
        # no duplicates
        if locale in locale_list:
            continue
        # if offered locales then check locale is offered
        if locales_offered and locale not in locales_offered:
            continue
        # remove if filtered out
        if locale in filtered_out:
            continue
        # ignore the default as it will be added first
        if locale == locale_default:
            continue
        locale_list.append(locale)
    # order the list if specified
    ordered_list = [locale_default]
    for locale in locale_order:
        if locale in locale_list:
            ordered_list.append(locale)
            # added so remove from our list
            locale_list.remove(locale)
    # add any remaining locales not ordered
    ordered_list += locale_list

    return ordered_list
开发者ID:CIOIL,项目名称:DataGovIL,代码行数:57,代码来源:i18n.py


示例13: defaultLocale

def defaultLocale():
    try:
        lang, _ = locale.getdefaultlocale()
    except Exception:
        lang = None

    if lang is not None:
        return Locale.parse(lang)
    else:
        return Locale.default()
开发者ID:kranthikumar,项目名称:muntjac,代码行数:10,代码来源:util.py


示例14: select_locale

def select_locale(choices):
    """Selects a locale."""
    enabled = set(settings.LANGUAGE_SECTIONS)
    for locale, quality in choices:
        try:
            locale = Locale.parse(locale, sep='-')
        except UnknownLocaleError:
            continue
        if str(locale) in enabled and \
           find_catalog(locale) is not None:
            return locale
    return Locale.parse(settings.DEFAULT_LANGUAGE)
开发者ID:sfermigier,项目名称:solace,代码行数:12,代码来源:__init__.py


示例15: select_locale

def select_locale(choices):
    """Selects a locale."""
    enabled = set(_settings['sections'])
    for locale, quality in choices:
        try:
            locale = Locale.parse(locale, sep='-')
        except UnknownLocaleError:
            continue
        if str(locale) in enabled and \
           find_catalog(locale) is not None:
            return locale
    return Locale.parse(_settings['default_language'])
开发者ID:passy,项目名称:glashammer-rdrei,代码行数:12,代码来源:__init__.py


示例16: list_translations

		def list_translations(dirname):
			if not os.path.isdir(dirname):
				return []
			result = []
			for folder in os.listdir(dirname):
				locale_dir = os.path.join(dirname, folder, 'LC_MESSAGES')
				if not os.path.isdir(locale_dir):
					continue
				if filter(lambda x: x.endswith('.mo'), os.listdir(locale_dir)):
					result.append(Locale.parse(folder))
			if not result:
				result.append(Locale.parse(self._default_locale))
			return result
开发者ID:MiddleMan5,项目名称:OctoPrint,代码行数:13,代码来源:flask.py


示例17: locales

 def locales(self):
     """
     returns a dict of locale codes to locale display names in both the current locale and the localized locale
     example: if the current locale is es_ES then locales['en_US'] = 'Ingles (Estados Unidos) - English (United States)'
     """
     locales = {}
     for l in config.locales:
         current_locale = Locale.parse(self.locale)
         language = current_locale.languages[l.split('_')[0]]
         territory = current_locale.territories[l.split('_')[1]]
         localized_locale_name = Locale.parse(l).display_name.capitalize()
         locales[l] = language.capitalize() + " (" + territory.capitalize() + ") - " + localized_locale_name
     return locales
开发者ID:necronet,项目名称:gae-boilerplate,代码行数:13,代码来源:basehandler.py


示例18: list_translations

		def list_translations(dirname):
			if not os.path.isdir(dirname):
				return []
			result = []
			for entry in scandir(dirname):
				locale_dir = os.path.join(entry.path, 'LC_MESSAGES')
				if not os.path.isdir(locale_dir):
					continue
				if filter(lambda x: x.name.endswith('.mo'), scandir(locale_dir)):
					result.append(Locale.parse(entry.name))
			if not result:
				result.append(Locale.parse(self._default_locale))
			return result
开发者ID:BigRep,项目名称:OctoPrint,代码行数:13,代码来源:flask.py


示例19: check_locale

 def check_locale(locale):
     if locale:
         try:
             Locale.parse(locale)
         except ValueError:
             return None
         except UnknownLocaleError:
             return None
         except Exception:
             traceback.print_exc()
             return None
         else:
             return locale
     return None
开发者ID:labsland,项目名称:weblabdeusto,代码行数:14,代码来源:i18n.py


示例20: get_languages

def get_languages():
    from babel import Locale
    from babel.core import UnknownLocaleError
    langs = []
    dir_names = [lang for lang in os.listdir(translations_path())
                       if lang != 'en_US']
    for name in dir_names:
        try:
            Locale.parse(name)
        except UnknownLocaleError:
            pass
        else:
            langs.append(name)
    langs.sort()
    langs.insert(0, 'en_US')
    return langs
开发者ID:TaraFife,项目名称:sagenb,代码行数:16,代码来源:misc.py



注:本文中的babel.Locale类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python _compat.text_type函数代码示例发布时间:2022-05-24
下一篇:
Python poweradminurt.PoweradminurtPlugin类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap