向APIException添加自定义响应头

2024-09-29 19:20:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个引用http://django-rest-framework.org/api-guide/exceptions.html的自定义异常。在

请知道我有自己的认证后端。因此,我没有使用rest\u框架的身份验证模块。在

对于身份验证错误,我想将“WWW Authenticate:Token”头添加到从异常发送的响应中。在

任何想法都会很有帮助。在

更新:

谢谢@Pathétique, 这就是我最后要做的。在

-有一个名为BaseView的基视图类。在

-重写handle_exception方法以设置适当的头,在我的示例中是“WWW Authenticate”。在

代码如下:

class BaseView(APIView):
  def handle_exception(self, exc):
     if isinstance(exc, MYEXCEPTION):
        self.headers['WWW-Authenticate'] = "Token"
        return Response({'detail': exc.detail,
                        status=exc.status_code, exception=True)

你的想法?在


Tags: djangoselftoken身份验证resthttpwwwstatus
2条回答

尝试在rest框架视图中重写finalize_response

def finalize_response(self, request, *args, **kwargs):
    response = super(SomeAPIView, self).finalize_response(request, *args, **kwargs)
    response['WWW-Authenticate'] = 'Token'
    return response

编辑:

在看到您的更新之后,我认为您对handle_exception的重写应该可以工作,我只添加一个else语句来调用父方法来覆盖其他异常。在重写dispatch的过程中,我注意到了一件事,即为self.headers导致了一个服务器错误,我没有花时间去追踪。不管怎样,看来你走对了。在

在身份验证类上使用authenticate_header方法。在

此外,这将确保您的响应也具有正确的401 Unauthorized状态代码集,而不是403 Forbidden。在

请看这里:http://django-rest-framework.org/api-guide/authentication.html#custom-authentication

相关问题 更多 >

    热门问题