【问题标题】:How to stop Django Rest Framework from rendering html for exceptions如何阻止 Django Rest Framework 为异常渲染 html
【发布时间】:2017-03-06 21:13:47
【问题描述】:

我在设置中设置了Debug=False 来测试我在客户端中的错误处理,但我从这个 api_view 中的异常中获取了一个 html 有效负载 (<h1>Server Error (500)</h1>):

@api_view(['POST', ])
@permission_classes((permissions.IsAuthenticated,))
@renderer_classes((JSONRenderer,))
@transaction.atomic()
def process_payment(request):

    # Do some work

    return Response(serializer.data)

我正在使用默认的 Accept 标头从 AngularJS 进行调用:Accept: application/json, text/plain, */*

Renderers 页面上的文档似乎表明,如果我明确使用 json 渲染器进行成功响应,我可以期待 json。

这是本地开发的副作用吗?如果可以的话,我不想编写代码来测试非 json 响应。

更新

我应该提到我在这次测试中使用了通配符 ALLOWED_HOSTS,所以我认为这不是问题。

查看 DRF 中的默认错误处理,看起来任何不是源自 APIException 或不是 Http404PermissionDenied 的异常都将导致 Response=None。这是我看到 html 响应的地方,因此解决方案可能是 Django 自定义错误处理程序,如下面的评论所示。

【问题讨论】:

标签: json django


【解决方案1】:

错误不能在 api_view 中。

这可能是配置错误。检查配置文件。检查您的 ALLOWED_HOSTS。

请参阅:https://docs.djangoproject.com/en/1.10/ref/settings/#std:setting-ALLOWED_HOSTS

【讨论】:

    【解决方案2】:

    我不知道这是否是最好的处理方式,但是通过在下面添加自定义 DRF 异常处理程序,未处理的异常现在将具有标准的 json 格式。

    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)
    
        # response == None is an exception not handled by the DRF framework in the call above
        if response is not None:
            response.data['status_code'] = response.status_code
        else:
            response = Response({'detail': 'Unhandled server error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            response.data['status_code'] = 500
    
            set_rollback()
    
        return response
    

    【讨论】:

      猜你喜欢
      • 2018-01-12
      • 2019-08-02
      • 1970-01-01
      • 2020-07-01
      • 2012-08-25
      • 2016-04-14
      • 2015-08-13
      • 2021-04-08
      • 2011-02-20
      相关资源
      最近更新 更多