想要 return 在 django rest 框架中的每次视图调用后来自中间件的响应

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

您好,我已经创建了用于检查用户身份验证的中间件

在另一台服务器上检查了用户身份验证,因此,每次请求出现时我都必须调用视图调用


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')

现在每次通话后,我都需要在回复中return user_id

我已经创建了 middle JSON 并正在尝试 return 以及每个视图调用。

但是当我尝试 return 中间 JSON

时看到的错误
(pdb) AttributeError: 'HttpResponse' object has no attribute 'render'

或者在终端上这样。

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

任何人都可以指导我如何进行。

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

提前致谢 问候

似乎您忘记将中间响应变成 json,在返回 HttpResponse

之前使用 middle = json.dumps(middle)

你可以试试这个,

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