【问题标题】:Django Rest - how can i return a custom json response when authentication fails?Django Rest - 身份验证失败时如何返回自定义 json 响应?
【发布时间】:2020-10-25 16:11:48
【问题描述】:

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

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)

现在,我不想引发异常或返回 HTTP 响应,而是想返回一个 JSON 字符串,例如:{'error': 'authentication failed'}。我知道如何从标准视图中做到这一点,但在这种情况下,我需要从中间件中做到这一点。我该怎么做?提前致谢!

【问题讨论】:

    标签: python django django-rest-framework


    【解决方案1】:

    你可以使用JsonResponse:

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

    【讨论】:

      猜你喜欢
      • 2019-02-02
      • 2020-03-16
      • 2017-03-01
      • 2013-03-01
      • 2018-02-18
      • 2023-03-19
      • 2020-02-17
      • 2022-08-16
      • 1970-01-01
      相关资源
      最近更新 更多