You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

middleware.py 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. class RedirectFallbackMiddleware(MiddlewareMixin):
  9. # Defined as class-level attributes to be subclassing-friendly.
  10. response_gone_class = HttpResponseGone
  11. response_redirect_class = HttpResponsePermanentRedirect
  12. def __init__(self, get_response=None):
  13. if not apps.is_installed('django.contrib.sites'):
  14. raise ImproperlyConfigured(
  15. "You cannot use RedirectFallbackMiddleware when "
  16. "django.contrib.sites is not installed."
  17. )
  18. super().__init__(get_response)
  19. def process_response(self, request, response):
  20. # No need to check for a redirect for non-404 responses.
  21. if response.status_code != 404:
  22. return response
  23. full_path = request.get_full_path()
  24. current_site = get_current_site(request)
  25. r = None
  26. try:
  27. r = Redirect.objects.get(site=current_site, old_path=full_path)
  28. except Redirect.DoesNotExist:
  29. pass
  30. if r is None and settings.APPEND_SLASH and not request.path.endswith('/'):
  31. try:
  32. r = Redirect.objects.get(
  33. site=current_site,
  34. old_path=request.get_full_path(force_append_slash=True),
  35. )
  36. except Redirect.DoesNotExist:
  37. pass
  38. if r is not None:
  39. if r.new_path == '':
  40. return self.response_gone_class()
  41. return self.response_redirect_class(r.new_path)
  42. # No redirect was found. Return the response.
  43. return response