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

 有海的地方最美_171 发布于 2023-02-03 10:29

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

例如:

@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)

mariodev.. 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})

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)


Carlton Gibs.. 6

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

像这样的东西:

# In urls.py
handler500 = 'my_app.views.api_500'

和:

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

我希望有所帮助.

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

    像这样的东西:

    # In urls.py
    handler500 = 'my_app.views.api_500'
    

    和:

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

    我希望有所帮助.

    2023-02-03 10:32 回答
  • 返回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})
    

    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)
    

    2023-02-03 10:32 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有