| 1 |
from django.apps import apps |
| 2 |
from django.conf import settings |
| 3 |
from django.contrib.redirects.models import Redirect |
| 4 |
from django.contrib.sites.shortcuts import get_current_site |
| 5 |
from django.core.exceptions import ImproperlyConfigured |
| 6 |
from django.http import HttpResponseGone, HttpResponsePermanentRedirect |
| 7 |
from django.utils.deprecation import MiddlewareMixin |
| 8 |
|
| 9 |
|
| 10 |
class RedirectFallbackMiddleware(MiddlewareMixin): |
| 11 |
# Defined as class-level attributes to be subclassing-friendly. |
| 12 |
response_gone_class = HttpResponseGone |
| 13 |
response_redirect_class = HttpResponsePermanentRedirect |
| 14 |
|
| 15 |
def __init__(self, get_response): |
| 16 |
if not apps.is_installed("django.contrib.sites"): |
| 17 |
raise ImproperlyConfigured( |
| 18 |
"You cannot use RedirectFallbackMiddleware when " |
| 19 |
"django.contrib.sites is not installed." |
| 20 |
) |
| 21 |
super().__init__(get_response) |
| 22 |
|
| 23 |
def process_response(self, request, response): |
| 24 |
# No need to check for a redirect for non-404 responses. |
| 25 |
if response.status_code != 404: |
| 26 |
return response |
| 27 |
|
| 28 |
full_path = request.get_full_path() |
| 29 |
current_site = get_current_site(request) |
| 30 |
|
| 31 |
r = None |
| 32 |
try: |
| 33 |
r = Redirect.objects.get(site=current_site, old_path=full_path) |
| 34 |
except Redirect.DoesNotExist: |
| 35 |
pass |
| 36 |
if r is None and settings.APPEND_SLASH and not request.path.endswith("/"): |
| 37 |
try: |
| 38 |
r = Redirect.objects.get( |
| 39 |
site=current_site, |
| 40 |
old_path=request.get_full_path(force_append_slash=True), |
| 41 |
) |
| 42 |
except Redirect.DoesNotExist: |
| 43 |
pass |
| 44 |
if r is not None: |
| 45 |
if r.new_path == "": |
| 46 |
return self.response_gone_class() |
| 47 |
return self.response_redirect_class(r.new_path) |
| 48 |
|
| 49 |
# No redirect was found. Return the response. |
| 50 |
return response |