如果在 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 在客户端上发送自定义响应。 欢迎任何建议。 谢谢。
最佳答案
您可以使用自定义异常处理程序来自定义 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
关于django - 如果 django rest 中提供了未经授权的凭据,如何发送自定义响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45941976/