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.3KB

123456789101112131415161718192021222324252627282930
  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 responsewith 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%s setting to insert "
  19. "'django.contrib.auth.middleware.AuthenticationMiddleware'." % (
  20. "_CLASSES" if settings.MIDDLEWARE is None else ""
  21. )
  22. )
  23. if request.method == 'HEAD' and (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS or
  24. (request.user.is_active and request.user.is_staff)):
  25. response = HttpResponse()
  26. response['X-View'] = get_view_name(view_func)
  27. return response