示例#1
0
 def test_request_urlconf_considered(self):
     request = RequestFactory().get('/nl/')
     request.urlconf = 'i18n.patterns.urls.default'
     middleware = LocaleMiddleware()
     with translation.override('nl'):
         middleware.process_request(request)
     self.assertEqual(request.LANGUAGE_CODE, 'nl')
示例#2
0
    def process_response(self, request, response):
        language = getattr(request, 'LANGUAGE_CODE',
                           self.get_language_from_request(request))
        local_middleware = LocaleMiddleware()
        response = local_middleware.process_response(request, response)
        path = unicode(request.path)

        # note: pages_root is assumed to end in '/'.
        #       testing this and throwing an exception otherwise, would probably be a good idea

        if not path.startswith(settings.MEDIA_URL) and \
                not path.startswith(settings.ADMIN_MEDIA_PREFIX) and \
                response.status_code == 200 and \
                response._headers['content-type'][1].split(';')[0] == "text/html":
            pages_root = urllib.unquote(reverse("pages-root"))
            try:
                decoded_response = response.content.decode('utf-8')
            except UnicodeDecodeError:
                decoded_response = response.content

            response.content = patch_response(decoded_response, pages_root,
                                              request.LANGUAGE_CODE)

        if (response.status_code == 301 or response.status_code == 302):
            location = response['Location']
            if not has_lang_prefix(location) and location.startswith("/") and \
                    not location.startswith(settings.MEDIA_URL) and \
                    not location.startswith(settings.ADMIN_MEDIA_PREFIX):
                response['Location'] = "/%s%s" % (language, location)
        response.set_cookie("django_language", language)
        return response
示例#3
0
 def test_request_urlconf_considered(self):
     request = RequestFactory().get('/nl/')
     request.urlconf = 'i18n.patterns.urls.default'
     middleware = LocaleMiddleware()
     with translation.override('nl'):
         middleware.process_request(request)
     self.assertEqual(request.LANGUAGE_CODE, 'nl')
示例#4
0
    def process_response(self, request, response):
        language = getattr(request, 'LANGUAGE_CODE', self.get_language_from_request(request))
        local_middleware = LocaleMiddleware()
        response =local_middleware.process_response(request, response)
        path = unicode(request.path)

        # note: pages_root is assumed to end in '/'.
        #       testing this and throwing an exception otherwise, would probably be a good idea

        if not path.startswith(settings.MEDIA_URL) and \
                not path.startswith(settings.ADMIN_MEDIA_PREFIX) and \
                response.status_code == 200 and \
                response._headers['content-type'][1].split(';')[0] == "text/html":
#            pages_root = urllib.unquote(reverse("pages-root"))
            try:
                decoded_response = response.content.decode('utf-8')
            except UnicodeDecodeError:
                decoded_response = response.content

#            response.content = patch_response(
#                decoded_response,
#                pages_root,
#                request.LANGUAGE_CODE
#            )

        if (response.status_code == 301 or response.status_code == 302 ):
            location = response['Location']
            if not has_lang_prefix(location) and location.startswith("/") and \
                    not location.startswith(settings.MEDIA_URL) and \
                    not location.startswith(settings.ADMIN_MEDIA_PREFIX):
                response['Location'] = "/%s%s" % (language, location)
        response.set_cookie("django_language", language)
        return response
示例#5
0
 def test_request_urlconf_considered(self):
     request = RequestFactory().get("/nl/")
     request.urlconf = "i18n.patterns.urls.default"
     middleware = LocaleMiddleware(lambda req: HttpResponse())
     with translation.override("nl"):
         middleware.process_request(request)
     self.assertEqual(request.LANGUAGE_CODE, "nl")
示例#6
0
    def process_response(self, request, response):
        language = getattr(request, 'LANGUAGE_CODE',
                           self.get_language_from_request(request))
        local_middleware = LocaleMiddleware()
        response = local_middleware.process_response(request, response)
        path = unicode(request.path)
        if not hasattr(request, 'session') and request.COOKIES.get(
                settings.LANGUAGE_COOKIE_NAME) != language:
            response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language)
        # note: pages_root is assumed to end in '/'.
        #       testing this and throwing an exception otherwise, would probably be a good idea

        if (not path.startswith(settings.MEDIA_URL)
                and not path.startswith(settings.STATIC_URL)
                and not (getattr(settings, 'STATIC_URL', False)
                         and path.startswith(settings.STATIC_URL))
                and response.status_code == 200
                and response.has_header('Content-Type')
                and response._headers['content-type'][1].split(';')[0]
                == "text/html"):
            pages_root = urllib.unquote(reverse("pages-root"))
            try:
                decoded_response = response.content.decode('utf-8')
            except UnicodeDecodeError:
                decoded_response = response.content

            response.content = patch_response(decoded_response, pages_root,
                                              request.LANGUAGE_CODE)

        if response.status_code == 301 or response.status_code == 302:
            location = response['Location']
            if location.startswith('.'):
                location = urlparse.urljoin(request.path, location)
                response['Location'] = location
            if (not has_lang_prefix(location) and location.startswith("/")
                    and not location.startswith(settings.MEDIA_URL)
                    and not (getattr(settings, 'STATIC_URL', False)
                             and location.startswith(settings.STATIC_URL))):
                response['Location'] = "/%s%s" % (language, location)
        if request.COOKIES.get('django_language') != language:
            response.set_cookie("django_language", language)
        return response
    def test_set_language(self):

        request = self.factory.post('/languages/',
                                    json.dumps({'lang': 'ru'}),
                                    content_type="application/json")
        smiddleware = SessionMiddleware()
        lmiddleware = LocaleMiddleware()
        smiddleware.process_request(request)
        lmiddleware.process_request(request)
        request.session.save()

        response = LanguagesView.as_view()(request)

        lmiddleware.process_response(request, response)

        self.assertEqual(response.status_code, 200)

        response_content = response.content

        if six.PY3:
            response_content = str(response_content, encoding='utf8')

        self.assertJSONEqual(response_content, {u'success': True})

        self.assertEqual(response['Content-Language'], u'ru')
示例#8
0
    def process_response(self, request, response):
        language = getattr(request, 'LANGUAGE_CODE', self.get_language_from_request(request))
        local_middleware = LocaleMiddleware()
        response = local_middleware.process_response(request, response)
        path = unicode(request.path)
        if not hasattr(request, 'session') and request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME) != language:
            response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language)
        # note: pages_root is assumed to end in '/'.
        #       testing this and throwing an exception otherwise, would probably be a good idea

        if (not path.startswith(settings.MEDIA_URL) and
                not path.startswith(settings.STATIC_URL) and
                not (getattr(settings, 'STATIC_URL', False) and path.startswith(settings.STATIC_URL)) and
                response.status_code == 200 and
                response.has_header('Content-Type') and
                response._headers['content-type'][1].split(';')[0] == "text/html"):
            pages_root = urllib.unquote(reverse("pages-root"))
            try:
                decoded_response = response.content.decode('utf-8')
            except UnicodeDecodeError:
                decoded_response = response.content

            response.content = patch_response(
                decoded_response,
                pages_root,
                request.LANGUAGE_CODE
            )

        if response.status_code == 301 or response.status_code == 302:
            location = response['Location']
            if location.startswith('.'):
                location = urlparse.urljoin(request.path, location)
                response['Location'] = location
            if (not has_lang_prefix(location) and location.startswith("/") and
                    not location.startswith(settings.MEDIA_URL) and
                    not (getattr(settings, 'STATIC_URL', False) and location.startswith(settings.STATIC_URL))):
                response['Location'] = "/%s%s" % (language, location)
        if request.COOKIES.get('django_language') != language:
            response.set_cookie("django_language", language)
        return response
示例#9
0
 def process_request(self, admin=False, headers=None, custom=False):
     headers = headers if headers else {}
     request = self.factory.get(reverse('django_js_context'), **headers)
     SessionMiddleware().process_request(request)
     LocaleMiddleware().process_request(request)
     if admin:
         request.user = User.objects.create_superuser('admin', '*****@*****.**', 'password')
     elif custom:
         from djangojs.fake.models import CustomUser
         request.user = CustomUser(identifier='custom')
     else:
         request.user = User.objects.create_user('user', '*****@*****.**', 'password')
     return self.get_result(request)
示例#10
0
    def process_response(self, request, response):
        language = getattr(request, 'LANGUAGE_CODE', self.get_language_from_request(request))
        local_middleware = LocaleMiddleware()
        response = local_middleware.process_response(request, response)
        path = force_unicode(request.path)

        # note: pages_root is assumed to end in '/'.
        # testing this and throwing an exception otherwise, would probably be a good idea
        pages_root = "/"

        if (True not in (path.startswith(p) for p in PATHS_NO_REDIRECTION)) and \
            response.status_code == 200 and \
            response['Content-Type'].split(';')[0] == "text/html":
            try:
                decoded_response = response.content.decode('utf-8')
            except UnicodeDecodeError:
                decoded_response = response.content

            # Customarily user pages are served from http://the.server.com/~username/
            #
            # The used regex is quite complex. The exact pattern depends on the used settings.
            # The regex extracts the path of the url without the leading page root, but only matches urls
            # that don't already contain a language string or aren't considered multilingual.
            #
            # Here is an annotated example pattern (_r_ is a shorthand for the value of pages_root):
            #   pattern:        <a([^>]+)href="(?=_r_)(?!(/fr/|/de/|/en/|/pt-br/|/media/|/media/admin/))(_r_([^"]*))"([^>]*)>
            #                     |-\1--|                |---------------------\2---------------------| |   |-\4--|| |-\5--|
            #                                                                                           |----\3----|
            #   input (_r_=/):  <a href="/admin/password_change/" class="foo">
            #   matched groups: (u' ', None, u'/admin/password_change/', u'admin/password_change/', u' class="foo"')
            #
            # Notice that (?=...) and (?!=...) do not consume input or produce a group in the match object.
            # If the regex matches, the extracted path we want is stored in the fourth group (\4).
            HREF_URL_FIX_RE = re.compile(ur'<a([^>]+)href="(?=%s)(?!(%s|%s))(%s([^"]*))"([^>]*)>' % (
                urllib.quote(pages_root),
                "|".join(map(lambda l: urllib.quote(pages_root) + l[0] + "/" , settings.LANGUAGES)),
                "|".join(PATHS_NO_REDIRECTION),
                urllib.quote(pages_root)
            ))

            # Unlike in href links, the '~' (see above) the '~' in form actions appears unquoted.
            #
            # For understanding this regex, please read the documentation for HREF_URL_FIX_RE above.
            FORM_URL_FIX_RE = re.compile(ur'<form([^>]+)action="(?=%s)(?!(%s|%s))(%s([^"]*))"([^>]*)>' % (
                pages_root,
                "|".join(map(lambda l: pages_root + l[0] + "/" , settings.LANGUAGES)),
                "|".join(PATHS_NO_REDIRECTION),
                pages_root
            ))

            # Documentation comments for HREF_URL_FIX_RE above explain each match group (\1, \4, \5) represents.
            decoded_response = HREF_URL_FIX_RE.sub(ur'<a\1href="%s%s/\4"\5>' % (pages_root, request.LANGUAGE_CODE), decoded_response)
            response.content = FORM_URL_FIX_RE.sub(ur'<form\1action="%s%s/\4"\5>' % (pages_root, request.LANGUAGE_CODE), decoded_response).encode("utf8")

        if response.status_code == 301 or response.status_code == 302:
            location = response['Location']
            if not has_lang_prefix(location) and location.startswith("/") and \
                (True not in (location.startswith(p) for p in PATHS_NO_REDIRECTION)):
                response['Location'] = "/%s%s" % (language, location)
        request.path = "/%s%s" % (language, path)
        request.path_info = "/%s%s" % (language, path)
        response.set_cookie("django_language", language)
        return response
示例#11
0
    def process_response(self, request, response):
        language = getattr(request, 'LANGUAGE_CODE',
                           self.get_language_from_request(request))
        local_middleware = LocaleMiddleware()
        response = local_middleware.process_response(request, response)
        path = unicode(request.path)

        # note: pages_root is assumed to end in '/'.
        #       testing this and throwing an exception otherwise, would probably be a good idea
        pages_root = urllib.unquote(reverse("pages-root"))

        if not path.startswith(settings.MEDIA_URL) and \
                not path.startswith(settings.ADMIN_MEDIA_PREFIX) and \
                response.status_code == 200 and \
                response._headers['content-type'][1].split(';')[0] == "text/html":
            try:
                decoded_response = response.content.decode('utf-8')
            except UnicodeDecodeError:
                decoded_response = response.content

            # Customarily user pages are served from http://the.server.com/~username/
            # When a user uses django-cms for his pages, the '~' of the url appears quoted in href links.
            # We have to quote pages_root for the regular expression to match.
            #
            # The used regex is quite complex. The exact pattern depends on the used settings.
            # The regex extracts the path of the url without the leading page root, but only matches urls
            # that don't already contain a language string or aren't considered multilingual.
            #
            # Here is an annotated example pattern (_r_ is a shorthand for the value of pages_root):
            #   pattern:        <a([^>]+)href="(?=_r_)(?!(/fr/|/de/|/en/|/pt-br/|/media/|/media/admin/))(_r_([^"]*))"([^>]*)>
            #                     |-\1--|                |---------------------\2---------------------| |   |-\4--|| |-\5--|
            #                                                                                           |----\3----|
            #   input (_r_=/):  <a href="/admin/password_change/" class="foo">
            #   matched groups: (u' ', None, u'/admin/password_change/', u'admin/password_change/', u' class="foo"')
            #
            # Notice that (?=...) and (?!=...) do not consume input or produce a group in the match object.
            # If the regex matches, the extracted path we want is stored in the fourth group (\4).
            HREF_URL_FIX_RE = re.compile(
                ur'<a([^>]+)href="(?=%s)(?!(%s|%s|%s))(%s([^"]*))"([^>]*)>' %
                (urllib.quote(pages_root), "|".join(
                    map(lambda l: urllib.quote(pages_root) + l[0] + "/",
                        settings.CMS_LANGUAGES)), settings.MEDIA_URL,
                 settings.ADMIN_MEDIA_PREFIX, urllib.quote(pages_root)))

            # Unlike in href links, the '~' (see above) the '~' in form actions appears unquoted.
            #
            # For understanding this regex, please read the documentation for HREF_URL_FIX_RE above.
            FORM_URL_FIX_RE = re.compile(
                ur'<form([^>]+)action="(?=%s)(?!(%s|%s|%s))(%s([^"]*))"([^>]*)>'
                % (pages_root, "|".join(
                    map(lambda l: pages_root + l[0] + "/",
                        settings.CMS_LANGUAGES)), settings.MEDIA_URL,
                   settings.ADMIN_MEDIA_PREFIX, pages_root))

            # Documentation comments for HREF_URL_FIX_RE above explain each match group (\1, \4, \5) represents.
            decoded_response = HREF_URL_FIX_RE.sub(
                ur'<a\1href="%s%s/\4"\5>' %
                (pages_root, request.LANGUAGE_CODE), decoded_response)
            response.content = FORM_URL_FIX_RE.sub(
                ur'<form\1action="%s%s/\4"\5>' %
                (pages_root, request.LANGUAGE_CODE),
                decoded_response).encode("utf8")

        if (response.status_code == 301 or response.status_code == 302):
            location = response['Location']
            if not has_lang_prefix(location) and location.startswith("/") and \
                    not location.startswith(settings.MEDIA_URL) and \
                    not location.startswith(settings.ADMIN_MEDIA_PREFIX):
                response['Location'] = "%s%s%s" % (
                    pages_root, language, location[len(pages_root) - 1:])
        response.set_cookie("django_language", language)
        return response
示例#12
0
 def is_language_prefix_patterns_used(urlconf):
     LocaleMiddleware().is_language_prefix_patterns_used