Django Rest-身份验证失败时如何返回自定义json响应?

时间:2020-10-25 16:11:48

标签: python django django-rest-framework

我创建了一个自定义中间件,以验证对我创建的API端点的每个获取请求。这是我的代码:

class TokenMiddleware(AuthenticationMiddleware):
    def process_request(self, request):

        if request.user.is_authenticated:
            return None
        else:     
            try:
                token = request.GET[TOKEN_QUERY_PUBLIC]
                secret = request.GET[TOKEN_QUERY_SECRET]
            except Exception as e:
                # A token isn't included in the query params
                raise ValidationError(detail=str(e))

            user = auth.authenticate(request, token=token, secret=secret)

            if user:
                auth.login(request, user)
            else:
                return HttpResponse('Authentication failed', status=404)

现在,我想返回一个JSON字符串,而不是引发异常或返回HTTP响应,例如:{'error': 'authentication failed'}。我知道我将如何从标准角度进行操作,但是在这种情况下,我需要从中间件进行操作。我该怎么做?预先感谢!

1 个答案:

答案 0 :(得分:1)

您可以使用JsonResponse

from django.http import JsonResponse

def process_request(self, request):
    ...
    return JsonResponse({'error': 'authentication failed'})