PageRenderTime 8ms CodeModel.GetById 1ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 0ms

/django/contrib/redirects/middleware.py

https://code.google.com/p/mango-py/
Python | 27 lines | 25 code | 1 blank | 1 comment | 6 complexity | a859f6d39c514d2bd073f8651c169c7c MD5 | raw file
 1from django.contrib.redirects.models import Redirect
 2from django import http
 3from django.conf import settings
 4
 5class RedirectFallbackMiddleware(object):
 6    def process_response(self, request, response):
 7        if response.status_code != 404:
 8            return response # No need to check for a redirect for non-404 responses.
 9        path = request.get_full_path()
10        try:
11            r = Redirect.objects.get(site__id__exact=settings.SITE_ID, old_path=path)
12        except Redirect.DoesNotExist:
13            r = None
14        if r is None and settings.APPEND_SLASH:
15            # Try removing the trailing slash.
16            try:
17                r = Redirect.objects.get(site__id__exact=settings.SITE_ID,
18                    old_path=path[:path.rfind('/')]+path[path.rfind('/')+1:])
19            except Redirect.DoesNotExist:
20                pass
21        if r is not None:
22            if r.new_path == '':
23                return http.HttpResponseGone()
24            return http.HttpResponsePermanentRedirect(r.new_path)
25
26        # No redirect was found. Return the response.
27        return response