Esempio n. 1
0
def get_language_from_request(request):
    """
    Analyzes the request to find what language the user wants the system to
    show. Only languages listed in settings.LANGUAGES are taken into account.
    If the user requests a sublanguage where we have a main language, we send
    out the main language.
    """
    global _supported
    if _supported is None:
        _supported = OrderedDict(settings.LANGUAGES)

    # Priority 1: User settings
    if request.user.is_authenticated():
        lang_code = request.user.locale
        if lang_code in _supported and lang_code is not None and check_for_language(lang_code):
            return lang_code

    # Priority 2: Anonymous user settings (session, cookie)
    if hasattr(request, 'session'):
        lang_code = request.session.get(LANGUAGE_SESSION_KEY)
        if lang_code in _supported and lang_code is not None and check_for_language(lang_code):
            return lang_code

    lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)
    try:
        return get_supported_language_variant(lang_code)
    except LookupError:
        pass

    # Priority 3: Event default
    if hasattr(request, 'event'):
        lang_code = request.event.locale
        try:
            return get_supported_language_variant(lang_code)
        except LookupError:
            pass

    # Priority 4: Browser default
    accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
    for accept_lang, unused in parse_accept_lang_header(accept):
        if accept_lang == '*':
            break

        if not language_code_re.search(accept_lang):
            continue

        try:
            return get_supported_language_variant(accept_lang)
        except LookupError:
            continue

    try:
        return get_supported_language_variant(settings.LANGUAGE_CODE)
    except LookupError:
        return settings.LANGUAGE_CODE
Esempio n. 2
0
def _get_language_from_request(request, user):
    """从请求中获取需要同步到用户个人信息的语言
    """
    supported_lang_codes = get_languages()
    # session 有language,说明在登录页面有进行修改或设置,则需要同步到用户个人信息中
    lang_code = request.session.get(translation.LANGUAGE_SESSION_KEY)
    if lang_code in supported_lang_codes and lang_code is not None and check_for_language(
            lang_code):
        return lang_code

    # 个人信息中已有language
    if user.language:
        return None

    # session 情况不满足同步到用户个人信息,且目前个人信息中无language设置
    # 查询header头
    accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
    for accept_lang, unused in parse_accept_lang_header(accept):
        if accept_lang == '*':
            break

        if not language_code_re.search(accept_lang):
            continue

        try:
            return get_supported_language_variant(accept_lang)
        except LookupError:
            continue

    # 使用settings默认设置
    try:
        return get_supported_language_variant(settings.LANGUAGE_CODE)
    except LookupError:
        return settings.LANGUAGE_CODE
Esempio n. 3
0
    def get_language_from_request(self, request):
        supported = dict(settings.LANGUAGES)
        accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
        for accept_lang, unused in parse_accept_lang_header(accept):
            if accept_lang == '*':
                break

            # We have a very restricted form for our language files
            # (no encoding specifier, since they all must be UTF-8 and
            # only one possible language each time. So we avoid the
            # overhead of gettext.find() and work out the MO file
            # manually.

            # 'normalized' is the root name of the locale in POSIX
            # format (which is the format used for the directories
            # holding the MO files).
            normalized = locale.locale_alias.get(to_locale(accept_lang, True))
            if not normalized:
                continue
            # Remove the default encoding from locale_alias.
            normalized = normalized.split('.')[0]

            for lang_code in (accept_lang, accept_lang.split('-')[0]):
                lang_code = lang_code.lower()
                if lang_code in supported and check_for_language(lang_code):
                    return lang_code
        return None
def get_language_from_request_and_is_from_path(request):  # noqa complexity-16
    """
    Analyzes the request to find what language the user wants the system to
    show. Only languages listed in settings.LANGUAGES are taken into account.
    If the user requests a sublanguage where we have a main language, we send
    out the main language. It also returns a value to determine if the language code
    was derived from a language code in the URL, or inferred from some other source.
    :returns: tuple of language code, boolean. The former can be None if the url being
    requested does not require translation, otherwise it should be a language code
    from the values in settings.LANGUAGES. The boolean should indicate whether the
    language code was calculated by reading a language code from the requested URL.
    In the case that it was, True should be returned, in the case where the URL language
    code was not used or not present, False is returned.
    """

    try:
        # If this is not a view that needs to be translated, return None, and be done with it!
        if not getattr(resolve(request.path_info).func, "translated", False):
            return None, False
    except Resolver404:
        # If this is an unrecognized URL, it may be redirectable to a language prefixed
        # URL, so let the language code setting carry on from here.
        pass

    supported_lang_codes = get_languages()

    lang_code = get_language_from_path(request.path_info)
    if lang_code in supported_lang_codes and lang_code is not None:
        return lang_code, True

    if hasattr(request, "session"):
        lang_code = request.session.get(LANGUAGE_SESSION_KEY)
        if (
            lang_code in supported_lang_codes
            and lang_code is not None
            and check_for_language(lang_code)
        ):
            return lang_code, False

    lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)

    try:
        return get_supported_language_variant(lang_code), False
    except LookupError:
        pass

    device_language = get_device_language()

    if device_language is not None:
        return device_language, False

    headers_language = get_accept_headers_language(request)

    if headers_language is not None:
        return headers_language, False

    return get_settings_language(), False
Esempio n. 5
0
def get_language_from_session_or_cookie(request: HttpRequest) -> str:
    if hasattr(request, 'session'):
        lang_code = request.session.get(LANGUAGE_SESSION_KEY)
        if lang_code in _supported and lang_code is not None and check_for_language(lang_code):
            return lang_code

    lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)
    try:
        return get_supported_language_variant(lang_code)
    except LookupError:
        pass
Esempio n. 6
0
def get_language_from_session_or_cookie(request) -> str:
    if hasattr(request, 'session'):
        lang_code = request.session.get(LANGUAGE_SESSION_KEY)
        if lang_code in _supported and lang_code is not None and check_for_language(lang_code):
            return lang_code

    lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)
    try:
        return get_supported_language_variant(lang_code)
    except LookupError:
        pass
Esempio n. 7
0
def get_supported_language_variant(raw_lang_code):
    """
    Returns the language-code that's listed in supported languages, possibly
    selecting a more generic variant. Raises LookupError if nothing found.

    The function will look for an alternative country-specific variant when the
    currently checked language code is not found. In Django, this behaviour can
    be avoided with the strict=True parameter, removed in this code.

    lru_cache should have a maxsize to prevent from memory exhaustion attacks,
    as the provided language codes are taken from the HTTP request. See also
    <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>.

    Based on Django 1.11.16's get_supported_language_variant from
    django/utils/translation/trans_real.py, with changes:

    * Language code can also be a Kuma language code
    * Return Kuma languge codes
    * Force strict=False to always allow fuzzy matching (zh-CHS gets zh-CN)
    """
    if raw_lang_code:
        # Kuma: Convert Kuma to Django language code
        lang_code = kuma_language_code_to_django(raw_lang_code)

        # Kuma: Check for known override
        if lang_code in settings.LOCALE_ALIASES:
            return settings.LOCALE_ALIASES[lang_code]

        # If 'fr-ca' is not supported, try special fallback or language-only 'fr'.
        possible_lang_codes = [lang_code]
        try:
            possible_lang_codes.extend(LANG_INFO[lang_code]['fallback'])
        except KeyError:
            pass
        generic_lang_code = lang_code.split('-')[0]
        possible_lang_codes.append(generic_lang_code)
        supported_lang_codes = get_django_languages()

        # Look for exact match
        for code in possible_lang_codes:
            if code in supported_lang_codes and check_for_language(code):
                # Kuma: Convert to Kuma language code
                return django_language_code_to_kuma(code)
        # If fr-fr is not supported, try fr-ca.
        for supported_code in supported_lang_codes:
            if supported_code.startswith(generic_lang_code + '-'):
                # Kuma: Convert to Kuma language code
                return django_language_code_to_kuma(supported_code)
    raise LookupError(raw_lang_code)
Esempio n. 8
0
File: i18n.py Progetto: Elchi3/kuma
def get_supported_language_variant(raw_lang_code):
    """
    Returns the language-code that's listed in supported languages, possibly
    selecting a more generic variant. Raises LookupError if nothing found.

    The function will look for an alternative country-specific variant when the
    currently checked language code is not found. In Django, this behaviour can
    be avoided with the strict=True parameter, removed in this code.

    lru_cache should have a maxsize to prevent from memory exhaustion attacks,
    as the provided language codes are taken from the HTTP request. See also
    <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>.

    Based on Django 1.11.16's get_supported_language_variant from
    django/utils/translation/trans_real.py, with changes:

    * Language code can also be a Kuma language code
    * Return Kuma languge codes
    * Force strict=False to always allow fuzzy matching (zh-CHS gets zh-CN)
    """
    if raw_lang_code:
        # Kuma: Convert Kuma to Django language code
        lang_code = kuma_language_code_to_django(raw_lang_code)

        # Kuma: Check for known override
        if lang_code in settings.LOCALE_ALIASES:
            return settings.LOCALE_ALIASES[lang_code]

        # If 'fr-ca' is not supported, try special fallback or language-only 'fr'.
        possible_lang_codes = [lang_code]
        try:
            possible_lang_codes.extend(LANG_INFO[lang_code]['fallback'])
        except KeyError:
            pass
        generic_lang_code = lang_code.split('-')[0]
        possible_lang_codes.append(generic_lang_code)
        supported_lang_codes = get_django_languages()

        # Look for exact match
        for code in possible_lang_codes:
            if code in supported_lang_codes and check_for_language(code):
                # Kuma: Convert to Kuma language code
                return django_language_code_to_kuma(code)
        # If fr-fr is not supported, try fr-ca.
        for supported_code in supported_lang_codes:
            if supported_code.startswith(generic_lang_code + '-'):
                # Kuma: Convert to Kuma language code
                return django_language_code_to_kuma(supported_code)
    raise LookupError(raw_lang_code)
Esempio n. 9
0
def get_language_from_request(request):  # noqa complexity-16
    """
    Analyzes the request to find what language the user wants the system to
    show. Only languages listed in settings.LANGUAGES are taken into account.
    If the user requests a sublanguage where we have a main language, we send
    out the main language.
    If check_path is True, the URL path prefix will be checked for a language
    code, otherwise this is skipped for backwards compatibility.
    """
    global DEVICE_LANGUAGE

    supported_lang_codes = get_languages()

    if hasattr(request, 'session'):
        lang_code = request.session.get(LANGUAGE_SESSION_KEY)
        if lang_code in supported_lang_codes and lang_code is not None and check_for_language(lang_code):
            return lang_code

    lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)

    try:
        return get_supported_language_variant(lang_code)
    except LookupError:
        pass

    accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
    for accept_lang, unused in parse_accept_lang_header(accept):
        if accept_lang == '*':
            break

        if not language_code_re.search(accept_lang):
            continue

        try:
            return get_supported_language_variant(accept_lang)
        except LookupError:
            continue

    try:
        if DEVICE_LANGUAGE is None:
            DEVICE_LANGUAGE = DeviceSettings.objects.get().language_id
        return get_supported_language_variant(DEVICE_LANGUAGE)
    except (DeviceSettings.DoesNotExist, LookupError):
        pass

    try:
        return get_supported_language_variant(settings.LANGUAGE_CODE)
    except LookupError:
        return settings.LANGUAGE_CODE
def set_language(request):
    lang_code = request.GET.get('LANGUAGES', 'ru')
    lang = get_language()
    if not lang_code:
        lang_code = request.GET.get('LANGUAGE_CODE', settings.LANGUAGE_CODE)
    next_url = request.META.get('HTTP_REFERER', None)
    if not is_safe_url:
        next_url = '/'
    response = http.HttpResponseRedirect(next_url)
    if lang_code and check_for_language(lang_code):
        if hasattr(request, 'session'):
            request.session['django_language'] = lang_code
        response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
        translation.activate(lang_code)
    return response
Esempio n. 11
0
def get_language_from_request(request, check_path=False):
    """
    Replacement for django.utils.translation.get_language_from_request.
    The portion of code that is modified is identified below with a comment.
    """
    if check_path:
        lang_code = get_language_from_path(request.path_info)
        if lang_code is not None:
            return lang_code

    lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)
    if lang_code is not None and lang_code in get_languages(
    ) and check_for_language(lang_code):
        return lang_code

    try:
        return get_supported_language_variant(lang_code)
    except LookupError:
        pass

    accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
    for accept_lang, unused in parse_accept_lang_header(accept):
        if accept_lang == '*':
            break

        # Convert lowercase region to uppercase before attempting to find a variant.
        # This is the only portion of code that is modified from the core function.
        accept_lang = language_code_to_iso_3166(accept_lang)

        if not language_code_re.search(accept_lang):
            continue

        try:
            return get_supported_language_variant(accept_lang)
        except LookupError:
            continue

    try:
        return get_supported_language_variant(settings.LANGUAGE_CODE)
    except LookupError:
        return settings.LANGUAGE_CODE
Esempio n. 12
0
def get_language_from_user_settings(request: HttpRequest) -> str:
    if request.user.is_authenticated:
        lang_code = request.user.locale
        if lang_code in _supported and lang_code is not None and check_for_language(lang_code):
            return lang_code
Esempio n. 13
0
def get_language_from_user_settings(request) -> str:
    if request.user.is_authenticated():
        lang_code = request.user.locale
        if lang_code in _supported and lang_code is not None and check_for_language(lang_code):
            return lang_code
Esempio n. 14
0
def get_language_from_customer_settings(request: HttpRequest) -> str:
    if getattr(request, 'customer', None):
        lang_code = request.customer.locale
        if lang_code in _supported and lang_code is not None and check_for_language(
                lang_code):
            return lang_code