2013-12-24 19:25:17 +08:00
|
|
|
from django.apps import apps
|
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
|
2014-01-26 04:54:25 +08:00
|
|
|
from django.contrib.sites.shortcuts import get_current_site
|
2013-02-08 23:32:09 +08:00
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2017-02-25 14:48:20 +08:00
|
|
|
from django.http import HttpResponseGone, HttpResponsePermanentRedirect
|
2016-06-14 15:41:58 +08:00
|
|
|
from django.utils.deprecation import MiddlewareMixin
|
2013-02-08 23:32:09 +08:00
|
|
|
|
2005-11-11 12:45:05 +08:00
|
|
|
|
2016-06-14 15:41:58 +08:00
|
|
|
class RedirectFallbackMiddleware(MiddlewareMixin):
|
2013-05-21 03:22:38 +08:00
|
|
|
# Defined as class-level attributes to be subclassing-friendly.
|
2017-02-25 14:48:20 +08:00
|
|
|
response_gone_class = HttpResponseGone
|
|
|
|
response_redirect_class = HttpResponsePermanentRedirect
|
2013-05-21 03:22:38 +08:00
|
|
|
|
2021-01-13 03:55:32 +08:00
|
|
|
def __init__(self, get_response):
|
2014-01-07 05:48:41 +08:00
|
|
|
if not apps.is_installed('django.contrib.sites'):
|
2013-02-08 23:32:09 +08:00
|
|
|
raise ImproperlyConfigured(
|
|
|
|
"You cannot use RedirectFallbackMiddleware when "
|
|
|
|
"django.contrib.sites is not installed."
|
|
|
|
)
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(get_response)
|
2015-11-07 23:12:37 +08:00
|
|
|
|
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
|
2015-03-23 03:04:31 +08:00
|
|
|
if r is None and settings.APPEND_SLASH and not request.path.endswith('/'):
|
2005-11-11 12:45:05 +08:00
|
|
|
try:
|
2015-03-23 03:04:31 +08:00
|
|
|
r = Redirect.objects.get(
|
|
|
|
site=current_site,
|
|
|
|
old_path=request.get_full_path(force_append_slash=True),
|
|
|
|
)
|
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
|