middleware.py 1.2 KB

12345678910111213141516171819202122232425262728
  1. from django.conf import settings
  2. from django.http import HttpResponse
  3. from django.utils.deprecation import MiddlewareMixin
  4. from .utils import get_view_name
  5. class XViewMiddleware(MiddlewareMixin):
  6. """
  7. Add an X-View header to internal HEAD requests.
  8. """
  9. def process_view(self, request, view_func, view_args, view_kwargs):
  10. """
  11. If the request method is HEAD and either the IP is internal or the
  12. user is a logged-in staff member, return a response with an x-view
  13. header indicating the view function. This is used to lookup the view
  14. function for an arbitrary page.
  15. """
  16. assert hasattr(request, 'user'), (
  17. "The XView middleware requires authentication middleware to be "
  18. "installed. Edit your MIDDLEWARE setting to insert "
  19. "'django.contrib.auth.middleware.AuthenticationMiddleware'."
  20. )
  21. if request.method == 'HEAD' and (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS or
  22. (request.user.is_active and request.user.is_staff)):
  23. response = HttpResponse()
  24. response.headers['X-View'] = get_view_name(view_func)
  25. return response