当前位置: 首页>>代码示例>>Python>>正文


Python babel.Locale类代码示例

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


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


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