2006-05-02 09:31:56 +08:00
|
|
|
from django.contrib.redirects.models import Redirect
|
2012-09-29 02:10:22 +08:00
|
|
|
from django.contrib.sites.models import get_current_site
|
2006-05-02 09:31:56 +08:00
|
|
|
from django import http
|
|
|
|
from django.conf import settings
|
2005-11-11 12:45:05 +08:00
|
|
|
|
2006-06-08 13:00:13 +08:00
|
|
|
class RedirectFallbackMiddleware(object):
|
2005-11-11 12:45:05 +08:00
|
|
|
def process_response(self, request, response):
|
|
|
|
if response.status_code != 404:
|
|
|
|
return response # No need to check for a redirect for non-404 responses.
|
|
|
|
path = request.get_full_path()
|
2012-09-29 02:10:22 +08:00
|
|
|
current_site = get_current_site(request)
|
2005-11-11 12:45:05 +08:00
|
|
|
try:
|
2012-09-29 02:10:22 +08:00
|
|
|
r = Redirect.objects.get(site__id__exact=current_site.id, old_path=path)
|
2006-05-02 09:31:56 +08:00
|
|
|
except Redirect.DoesNotExist:
|
2005-11-11 12:45:05 +08:00
|
|
|
r = None
|
2006-05-02 09:31:56 +08:00
|
|
|
if r is None and settings.APPEND_SLASH:
|
2005-11-11 12:45:05 +08:00
|
|
|
# Try removing the trailing slash.
|
|
|
|
try:
|
2012-09-29 02:10:22 +08:00
|
|
|
r = Redirect.objects.get(site__id__exact=current_site.id,
|
2006-05-02 09:31:56 +08:00
|
|
|
old_path=path[:path.rfind('/')]+path[path.rfind('/')+1:])
|
|
|
|
except Redirect.DoesNotExist:
|
2005-11-11 12:45:05 +08:00
|
|
|
pass
|
|
|
|
if r is not None:
|
2007-06-20 14:01:16 +08:00
|
|
|
if r.new_path == '':
|
2006-05-02 09:31:56 +08:00
|
|
|
return http.HttpResponseGone()
|
|
|
|
return http.HttpResponsePermanentRedirect(r.new_path)
|
2005-11-11 12:45:05 +08:00
|
|
|
|
|
|
|
# No redirect was found. Return the response.
|
|
|
|
return response
|