如果在django rest中提供了未经过授权的凭据,如何发送自定义响应

时间:2017-08-29 14:38:54

标签: django django-rest-framework django-authentication django-rest-auth

如果在django rest中提供了未经授权的凭据,如何发送自定义响应。

class StockList(APIView):
    permission_classes = [IsAuthenticated]

    def get(self,request):
         stocks = Stock.objects.all()
         serializer = StockSerializer(stocks,many=True)
         return Response({'user': serializer.data,'post': serializer.data})
    def post(self):
         pass

这里当我用无效凭据命中url时,我在开发服务器上遇到401错误。 但我想使用json在客户端发送自定义响应。 欢迎任何建议。 谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用自定义异常处理程序来自定义api异常的响应。

from rest_framework.views import exception_handler
def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.
    if response is not None:
        response.data['status_code'] = response.status_code

    if response.status_code == 401:
        response.data['some_message'] = "Some custom message"

    return response

然后在setting.py中,您必须添加自定义错误处理程序

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'my_project.path.to.custom_exception_handler'
}

参考:docs