middleware.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. from __future__ import unicode_literals
  2. from django.conf import settings
  3. from django.contrib.redirects.models import Redirect
  4. from django.contrib.sites.models import get_current_site
  5. from django.core.exceptions import ImproperlyConfigured
  6. from django import http
  7. class RedirectFallbackMiddleware(object):
  8. def __init__(self):
  9. if 'django.contrib.sites' not in settings.INSTALLED_APPS:
  10. raise ImproperlyConfigured(
  11. "You cannot use RedirectFallbackMiddleware when "
  12. "django.contrib.sites is not installed."
  13. )
  14. def process_response(self, request, response):
  15. if response.status_code != 404:
  16. return response # No need to check for a redirect for non-404 responses.
  17. full_path = request.get_full_path()
  18. current_site = get_current_site(request)
  19. r = None
  20. try:
  21. r = Redirect.objects.get(site=current_site, old_path=full_path)
  22. except Redirect.DoesNotExist:
  23. pass
  24. if settings.APPEND_SLASH and not request.path.endswith('/'):
  25. # Try appending a trailing slash.
  26. path_len = len(request.path)
  27. full_path = full_path[:path_len] + '/' + full_path[path_len:]
  28. try:
  29. r = Redirect.objects.get(site=current_site, old_path=full_path)
  30. except Redirect.DoesNotExist:
  31. pass
  32. if r is not None:
  33. if r.new_path == '':
  34. return http.HttpResponseGone()
  35. return http.HttpResponsePermanentRedirect(r.new_path)
  36. # No redirect was found. Return the response.
  37. return response