Python django.utils.translation 模块,to_locale() 实例源码

我们从Python开源项目中,提取了以下10个代码示例,用于说明如何使用django.utils.translation.to_locale()

项目:zing    作者:evernote    | 项目源码 | 文件源码
def process_request(self, request):
        # Under Windows, locale names are different, setlocale() with regular
        # locale names will fail and locale.setlocale(locale.LC_ALL, '') will
        # produce side effect seems like the safest option is just not set any
        # locale at all
        if os.name == 'nt':
            return

        # FIXME: some languages like arabic don't have a language only locale
        # for no good reason. we need a function to pick default locale for
        # these
        lang = translation.to_locale(translation.get_language())
        try:
            if lang == 'tr' or lang.startswith('tr_'):
                raise ValueError("Turkish locale broken due to changed "
                                 "meaning of lower()")
            locale.setlocale(locale.LC_ALL, (lang, 'UTF-8'))
        except:
            logging.debug('Failed to set locale to %s; using Pootle default',
                          lang)
            set_pootle_locale_from_settings()
项目:zing    作者:evernote    | 项目源码 | 文件源码
def set_pootle_locale_from_settings():
    """Try to set Pootle locale based on the language specified in settings."""

    # See above for the reasoning why we need to skip setting locale under
    # Windows
    if os.name == 'nt':
        return

    lang = translation.to_locale(settings.LANGUAGE_CODE)
    try:
        if lang == 'tr' or lang.startswith('tr_'):
            raise ValueError("Turkish locale broken due to changed meaning of "
                             "lower()")
        locale.setlocale(locale.LC_ALL, (lang, 'UTF-8'))
    except:
        logging.debug('Failed to set locale to Pootle default (%s); loading '
                      'system default', lang)
        locale.setlocale(locale.LC_ALL, '')
项目:zing    作者:evernote    | 项目源码 | 文件源码
def get_alt_src_langs(request, user, translation_project):
    language = translation_project.language
    project = translation_project.project
    source_language = project.source_language

    langs = user.alt_src_langs.exclude(
        id__in=(language.id, source_language.id)
    ).filter(translationproject__project=project)

    if not user.alt_src_langs.count():
        from pootle_language.models import Language
        accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')

        for accept_lang, __ in parse_accept_lang_header(accept):
            if accept_lang == '*':
                continue

            simplified = data.simplify_to_common(accept_lang)
            normalized = to_locale(data.normalize_code(simplified))
            code = to_locale(accept_lang)
            if (normalized in
                    ('en', 'en_US', source_language.code, language.code) or
                code in ('en', 'en_US', source_language.code, language.code)):
                continue

            langs = Language.objects.filter(
                code__in=(normalized, code),
                translationproject__project=project,
            )
            if langs.count():
                break

    return langs


#
# Views used with XMLHttpRequest requests.
#
项目:zing    作者:evernote    | 项目源码 | 文件源码
def tr_lang(language_name):
    """Translates language names."""
    language_code = translation.get_language()
    if language_code is None:
        language_code = settings.LANGUAGE_CODE
    language_code = translation.to_locale(language_code)

    return langdata.tr_lang(language_code)(language_name)
项目:django-twilio-tfa    作者:rtindru    | 项目源码 | 文件源码
def get_default_locale_callable():
    """
    Wrapper function so that the default mapping is only built when needed
    """
    exec_dir = os.path.dirname(os.path.realpath(__file__))
    xml_path = os.path.join(exec_dir, 'data', 'FacebookLocales.xml')

    fb_locales = _build_locale_table(xml_path)

    def default_locale(request):
        """
        Guess an appropiate FB locale based on the active Django locale.
        If the active locale is available, it is returned. Otherwise,
        it tries to return another locale with the same language. If there
        isn't one avaible, 'en_US' is returned.
        """
        chosen = 'en_US'
        language = get_language()
        if language:
            locale = to_locale(language)
            lang, _, reg = locale.partition('_')

            lang_map = fb_locales.get(lang)
            if lang_map is not None:
                if reg in lang_map['regs']:
                    chosen = lang + '_' + reg
                else:
                    chosen = lang + '_' + lang_map['default']
        return chosen

    return default_locale
项目:django-admin-caching    作者:PaesslerAG    | 项目源码 | 文件源码
def i18n_l10n_prefix(self):
        parts = []
        lang = translation.get_language()
        if lang is None:
            lang = ''
            locale = ''
        else:
            locale = translation.to_locale(lang)
        if settings.USE_I18N:
            parts += [lang]
        if settings.USE_L10N:
            parts += [locale]
        return '.'.join(parts)
项目:deb-python-django-babel    作者:openstack    | 项目源码 | 文件源码
def _get_format():
    locale = get_current_locale()
    if not locale:
        locale = babel_core.Locale.parse(to_locale(get_language()))
    if timezone:
        tzinfo = timezone(settings.TIME_ZONE)
    else:
        tzinfo = None
    return babel_support.Format(locale, tzinfo)
项目:open-synthesis    作者:twschiller    | 项目源码 | 文件源码
def get_current_locale():
    """Return the locale for the current language."""
    return to_locale(get_language())
项目:Provo-Housing-Database    作者:marcopete5    | 项目源码 | 文件源码
def get_default_locale_callable():
    """
    Wrapper function so that the default mapping is only built when needed
    """
    exec_dir = os.path.dirname(os.path.realpath(__file__))
    xml_path = os.path.join(exec_dir, 'data', 'FacebookLocales.xml')

    fb_locales = _build_locale_table(xml_path)

    def default_locale(request):
        """
        Guess an appropiate FB locale based on the active Django locale.
        If the active locale is available, it is returned. Otherwise,
        it tries to return another locale with the same language. If there
        isn't one avaible, 'en_US' is returned.
        """
        chosen = 'en_US'
        language = get_language()
        if language:
            locale = to_locale(language)
            lang, _, reg = locale.partition('_')

            lang_map = fb_locales.get(lang)
            if lang_map is not None:
                if reg in lang_map['regs']:
                    chosen = lang + '_' + reg
                else:
                    chosen = lang + '_' + lang_map['default']
        return chosen

    return default_locale
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(UserSettingsForm, self).__init__(*args, **kwargs)

        # Languages
        def get_language_display_name(code, desc):
            try:
                desc = translation.get_language_info(code)['name_local']
                desc = string.capwords(desc)
            except KeyError:
                # If a language is not defined in django.conf.locale.LANG_INFO
                # get_language_info raises KeyError
                pass
            return "%s (%s)" % (desc, code)
        languages = [(k, get_language_display_name(k, v))
                     for k, v in settings.LANGUAGES]
        self.fields['language'].choices = languages

        # Timezones
        timezones = []
        language = translation.get_language()
        current_locale = translation.to_locale(language)
        babel_locale = babel.Locale.parse(current_locale)
        for tz, offset in self._sorted_zones():
            try:
                utc_offset = _("UTC %(hour)s:%(min)s") % {"hour": offset[:3],
                                                          "min": offset[3:]}
            except Exception:
                utc_offset = ""

            if tz == "UTC":
                tz_name = _("UTC")
            elif tz == "GMT":
                tz_name = _("GMT")
            else:
                tz_label = babel.dates.get_timezone_location(
                    tz, locale=babel_locale)
                # Translators:  UTC offset and timezone label
                tz_name = _("%(offset)s: %(label)s") % {"offset": utc_offset,
                                                        "label": tz_label}
            timezones.append((tz, tz_name))

        self.fields['timezone'].choices = timezones

        # When we define a help_text using any variable together with
        # form field, traslation does not work well.
        # To avoid this, we define here. (#1563021)
        self.fields['pagesize'].help_text = (
            _("Number of items to show per page (applies to the pages "
              "that have API supported pagination, Max Value: %s)")
            % self.max_value)