3

提供如何发送定制的响应,如果未经授权的凭据在Django休息提供如何发送定制的响应。如果unauthroized凭据在Django休息

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发送自定义响应。 欢迎任何建议。 谢谢。

+0

你要发送的所有401错误自定义响应? –

+0

@arpit索兰奇是 –

回答

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

+0

我看到了,但不能figureout如何在我的代码实现这一点。所以请在我的代码 –

+0

中操纵这一点,你无法弄清楚。把上面的代码放在任何文件中,并在settings.py文件中给出它的路径 –

+0

做到了这一点,但现在显示valueerror为空模块名称 –