想要在django-rest框架中的每次视图调用后返回中间件的响应



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

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


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

现在,每次调用后,我都需要在响应中返回user_id

我已经创建了middle JSON,并试图在每次视图调用时返回。

但是当我试图返回中间的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

提前感谢问候

你可以试试这个,

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

在返回HttpResponse 之前,似乎忘记了使用middle = json.dumps(middle)将中间响应转换为json

最新更新