如何使用django rest框架禁用HTML错误页面的返回?

mam*_*mcx 13 django rest exception django-rest-framework

如果我在DRF的lib之外有错误,则django会发回错误的HTML而不是DRF使用的正确错误响应.

例如:

@api_view(['POST'])
@permission_classes((IsAuthenticated,))
def downloadData(request):
    print request.POST['tables']
Run Code Online (Sandbox Code Playgroud)

返回异常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)
Run Code Online (Sandbox Code Playgroud)

mar*_*dev 9

返回json的一种方法是捕获异常并返回正确的响应(假设您使用的JSONParser是默认解析器):

from rest_framework.response import Response
from rest_framework import status


@api_view(['POST'])
@permission_classes((IsAuthenticated,))
def downloadData(request):
    try:
        print request.POST['tables']
    except:
        return Response({'error': True, 'content': 'Exception!'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    return Response({'error': False})
Run Code Online (Sandbox Code Playgroud)

UPDATE

对于全局明智的用例,正确的想法是将json响应放在异常中间件中.

您可以在此博客文章中找到示例.

在您的情况下,您需要返回DRF响应,因此如果引发任何异常,它将最终出现在process_exception:

from rest_framework.response import Response


class ExceptionMiddleware(object):

    def process_exception(self, request, exception):
        return Response({'error': True, 'content': exception}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Run Code Online (Sandbox Code Playgroud)


Car*_*son 6

您可以通过在URLConf中指定自定义处理程序来替换默认错误处理程序,如此处所述

像这样的东西:

# In urls.py
handler500 = 'my_app.views.api_500'
Run Code Online (Sandbox Code Playgroud)

和:

# In my_app.views
def api_500(request):
    response = HttpResponse('{"detail":"An Error Occurred"}', content_type="application/json", status=500)
    return response
Run Code Online (Sandbox Code Playgroud)

我希望有所帮助.