2013-02-08 05:35:23 +08:00
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2013-02-08 23:32:09 +08:00
|
|
|
from django.conf import settings
|
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
|
2013-02-08 23:32:09 +08:00
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2006-05-02 09:31:56 +08:00
|
|
|
from django import http
|
2013-02-08 23:32:09 +08:00
|
|
|
|
2005-11-11 12:45:05 +08:00
|
|
|
|
2006-06-08 13:00:13 +08:00
|
|
|
class RedirectFallbackMiddleware(object):
|
2013-05-21 03:22:38 +08:00
|
|
|
|
|
|
|
# Defined as class-level attributes to be subclassing-friendly.
|
|
|
|
response_gone_class = http.HttpResponseGone
|
|
|
|
response_redirect_class = http.HttpResponsePermanentRedirect
|
|
|
|
|
2013-02-08 23:32:09 +08:00
|
|
|
def __init__(self):
|
|
|
|
if 'django.contrib.sites' not in settings.INSTALLED_APPS:
|
|
|
|
raise ImproperlyConfigured(
|
|
|
|
"You cannot use RedirectFallbackMiddleware when "
|
|
|
|
"django.contrib.sites is not installed."
|
|
|
|
)
|
|
|
|
|
2005-11-11 12:45:05 +08:00
|
|
|
def process_response(self, request, response):
|
2013-05-21 03:22:38 +08:00
|
|
|
# No need to check for a redirect for non-404 responses.
|
2005-11-11 12:45:05 +08:00
|
|
|
if response.status_code != 404:
|
2013-05-21 03:22:38 +08:00
|
|
|
return response
|
2013-02-08 05:35:23 +08:00
|
|
|
|
|
|
|
full_path = request.get_full_path()
|
2012-09-29 02:10:22 +08:00
|
|
|
current_site = get_current_site(request)
|
2013-02-08 05:35:23 +08:00
|
|
|
|
|
|
|
r = None
|
2005-11-11 12:45:05 +08:00
|
|
|
try:
|
2013-02-08 05:35:23 +08:00
|
|
|
r = Redirect.objects.get(site=current_site, old_path=full_path)
|
2006-05-02 09:31:56 +08:00
|
|
|
except Redirect.DoesNotExist:
|
2013-02-08 05:35:23 +08:00
|
|
|
pass
|
|
|
|
if settings.APPEND_SLASH and not request.path.endswith('/'):
|
|
|
|
# Try appending a trailing slash.
|
|
|
|
path_len = len(request.path)
|
|
|
|
full_path = full_path[:path_len] + '/' + full_path[path_len:]
|
2005-11-11 12:45:05 +08:00
|
|
|
try:
|
2013-02-08 05:35:23 +08:00
|
|
|
r = Redirect.objects.get(site=current_site, old_path=full_path)
|
2006-05-02 09:31:56 +08:00
|
|
|
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 == '':
|
2013-05-21 03:22:38 +08:00
|
|
|
return self.response_gone_class()
|
|
|
|
return self.response_redirect_class(r.new_path)
|
2005-11-11 12:45:05 +08:00
|
|
|
|
|
|
|
# No redirect was found. Return the response.
|
|
|
|
return response
|