[Django]-How to return an rest_framework.response object from a django custom middleware class?

44đź‘Ť

âś…

I’ve just recently hit this problem. This solution doesn’t use the Django Rest Framework Response, but if your server just returns JSON this solution might work for you.

New in django 1.7 or greater is the JSONResponse response type.

https://docs.djangoproject.com/en/3.0/ref/request-response/#jsonresponse-objects

In the middleware you can return these responses without having all the “No accepted renderers” and “Response has no attribute encode” errors.

It’s very similar format to the DRF Response

The import is as follows:
from django.http import JsonResponse

And how you use it:

return JsonResponse({'error': 'Some error'}, status=401)

Hopefully this helps you out!

👤Jordan

19đź‘Ť

I’ve solved this myself by mimicking how rest frameworks views patch the response object with accepted_renderer, accepted_media_type, and renderer_context. In my case I just wanted to return a 401 response using rest frameworks Response class, partly because my tests expect a rest framework response when I call self.client.get(...) and assert response.data.

Other use cases may require you to provide additional info in the renderer_context or use a different accepted_renderer.

from rest_framework import status
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response

class MiddlewareClass(object):

    def __init__(self, get_response):
        self.get_response = get_response

    def unauthorized_response(self, request):
        response = Response(
            {"detail": "This action is not authorized"},
            content_type="application/json",
            status=status.HTTP_401_UNAUTHORIZED,
        )
        response.accepted_renderer = JSONRenderer()
        response.accepted_media_type = "application/json"
        response.renderer_context = {}

        return response

    def __call__(self, request: HttpRequest):
        if not self.authorized(request):
            return self.unauthorized_response(request)
        return self.get_response(request)
👤A. J. Parr

1đź‘Ť

Down voted the answer above as it doesn’t work for me.
The neighbor answer isn’t helpful, too.
Both still return ContentNotRenderedError without manual call of the .render() method.
Tested with Python 3.8, Django 2.2, DRF 3.12.1.

The working mimicking middleware method for me is:

from rest_framework.views import APIView

# ... in the middleware class

    def __call__(self, request):
        try:
            # Middleware logic before calling a view.
        except APIException as err:
            # No DRF auto-wrap out of view, so let's do it manually.
            response = some_exception_handler(err, {})
            return self.django_response(request, response)

        return self.get_response(request)

    def django_response(self, request: HttpRequest, resp: Response) -> HttpResponse:
        view = APIView()
        # copy-pasted from APIView.dispatch
        view.headers = view.default_response_headers
        return view.finalize_response(request, resp).render()

Docs investigation

To support my doubts about other solutions, here’s the problem with an exception in middleware before the view has been called.

I bet the .render() method cannot be called automatically, cause the docs say:

There are three circumstances under which a TemplateResponse will be rendered:

  • When the TemplateResponse instance is explicitly rendered, using the SimpleTemplateResponse.render() method.
  • When the content of the response is explicitly set by assigning response.content.
  • After passing through template response middleware, but before passing through response middleware.

In our case only the 3-rd option matches. So, what is that "template response middleware"? There’s only one similar thing in the docs:

process_template_response() is called just after the view has finished executing, if the response instance has a render() method, indicating that it is a TemplateResponse or equivalent.

But we haven’t reached the view being executed! That’s why the .render() method won’t be called in our case.

Leave a comment