コード例 #1
0
def set_language_and_region(request, region_code="GL", language_code="en"):
    """
    Adapted from the Django's set_language

    Redirect to a given url while setting the chosen language in the
    session or cookie. The url and the language code need to be
    specified in the request parameters, or will be taken from HTTP_REFERER
    """
    next_url = request.POST.get('next', request.GET.get('next'))
    if not is_safe_url(url=next_url, host=request.get_host()):
        next_url = request.META.get('HTTP_REFERER')
        if not is_safe_url(url=next_url, host=request.get_host()):
            next_url = '/GL/en/'  # Default global region with English language.
    # In case of bogus information fall back to default region or language for that region if exists.
    region, new_language_code = get_region(region_code, language_code)
    if new_language_code != language_code:
        language_code = new_language_code

    old_path = URL(next_url).path
    if old_path == "/":
        new_path = "/%s/" % "/".join([region.code, language_code])
    else:
        new_path = "/" + "/".join([region.code, language_code] + old_path.split("/")[3:])
    next_url = URL(next_url).replace(path=new_path)
    response = http.HttpResponseRedirect(next_url)

    if hasattr(request, 'session'):
        request.session[LANGUAGE_SESSION_KEY] = language_code
    else:
        response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language_code,
                            max_age=settings.LANGUAGE_COOKIE_AGE,
                            path=settings.LANGUAGE_COOKIE_PATH,
                            domain=settings.LANGUAGE_COOKIE_DOMAIN)
    return response