Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-viewsdjango-rest-framework-simplejwt

Want to return response from middleware after every view call in django rest framework


Hi I have created middleware for checking user authentication

User Authentication is been checked on another server, therefore, I have to call every time a request comes on view call


class CheckUserMiddleware:
    """Check User logged-in"""

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

    def __call__(self, request):
        """code to be executed every time view is called"""

        response = self.get_response(request)
        return response
   

    def process_view(self, request, view_func, view_args, view_kwargs):
        """ checks weather user is valid or not """
        token_info  = request.headers['Authorization']
        # request._result = get_user(token_info, url)
        result      = get_user(token_info, url)
        if result.status_code == 200:
            return None
        else:
            status_code = status.HTTP_401_UNAUTHORIZED
            message = "Token is invalid or expired"
            token_type = "access"
            detail = "Given token not valid for any token type"
            result = {
                'message'   : message,
                'token_type': token_type,
                'detail'    : detail,
                'status'    : status_code,
            }
            result = json.dumps(result)
            return HttpResponse(content=result, content_type='application/json')

    def process_template_response(self, request, response):
        """return template response"""

        token_info    = request.headers['Authorization']
        result        = get_user(token_info, url)
        status_code   = status.HTTP_200_OK
        json_response = result.json()
        email         = json_response['email']
        user_id       = json_response['user_id']
        user_type     = json_response['user_profile'][0]['user_type']
        middle = {
            'eamil'         : email,
            'user_id'       : user_id,
            'user_type'     : user_type,
        }

        return HttpResponse(content=middle, content_type='application/json')

Now after every call, I need to return user_id in the response

I have created middle JSON and am trying to return along with every view call.

but the error that I see when I try to return middle JSON

(pdb) AttributeError: 'HttpResponse' object has no attribute 'render'

or this on the terminal.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 9735: ordinal not in range(128)

Can anyone please guide me on how should I proceed.

Please Note: Process View is working fine, I find issue persists in process_template_response

Thanks in advance Regards


Solution

  • you can try this out,

    from rest_framework.renderers import JSONRenderer
    from rest_framework.response import Response
    
    def process_view(self, request, view_func, view_args, view_kwargs):
        response = Response(
            data={}, status=status.HTTP_200_OK
        )
        response.accepted_renderer = JSONRenderer()
        response.accepted_media_type = "application/json"
        response.renderer_context = {}
        return response