我创建了一个引用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)
你的想法?在
尝试在rest框架视图中重写
finalize_response
:编辑:
在看到您的更新之后,我认为您对
handle_exception
的重写应该可以工作,我只添加一个else语句来调用父方法来覆盖其他异常。在重写dispatch的过程中,我注意到了一件事,即为self.headers导致了一个服务器错误,我没有花时间去追踪。不管怎样,看来你走对了。在在身份验证类上使用
authenticate_header
方法。在此外,这将确保您的响应也具有正确的
401 Unauthorized
状态代码集,而不是403 Forbidden
。在请看这里:http://django-rest-framework.org/api-guide/authentication.html#custom-authentication
相关问题 更多 >
编程相关推荐