如果我在DRF的库之外有错误,django会发回错误的HTML而不是DRF正确的错误响应。如何禁用django rest框架返回HTML错误页面?
例如:
@api_view(['POST'])
@permission_classes((IsAuthenticated,))
def downloadData(request):
print request.POST['tables']
返回异常MultiValueDictKeyError: "'tables'"
。并取回完整的HTML。如何只得到一个JSON的错误?
PD:
这是最后的代码:
@api_view(['GET', 'POST'])
def process_exception(request, exception):
# response = json.dumps({'status': status.HTTP_500_INTERNAL_SERVER_ERROR,
# 'message': str(exception)})
# return HttpResponse(response,
# content_type='application/json; charset=utf-8')
return Response({
'error': True,
'content': unicode(exception)},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
class ExceptionMiddleware(object):
def process_exception(self, request, exception):
# response = json.dumps({'status': status.HTTP_500_INTERNAL_SERVER_ERROR,
# 'message': str(exception)})
# return HttpResponse(response,
# content_type='application/json; charset=utf-8')
print exception
return process_exception(request, exception)
是的,但那requiere修补每个视图。我想知道是否存在可以在全球范围内使用的东西 – mamcx
@mamcx我已经更新了我的答案。请看一下。 – mariodev
不错,@mariodev。 DRF应该包含这个,它是JSON API返回HTML的糟糕形式。也许你应该提交它? ;-) – s29