如何实现自定义server_error,以正确的格式呈现响应内容?

时间:2014-07-04 03:34:53

标签: django-rest-framework

我有一个自定义server_error函数,使用DRF返回500错误的json响应:

def api_server_error(request, template_name=None):

    return HttpResponseServerError(json.dumps({'detail': 'Internal server error'}),
                                   content_type="application/json", status=500)

但我真正想做的是以请求的格式呈现响应,例如xml,json等。我该怎么做?

2 个答案:

答案 0 :(得分:1)

通过返回drf回复:

from rest_framework.response import Response
from rest_framework import status

return Response({'detail' : "Internal server error"}, status = status.HTTP_500_INTERNAL_SERVER_ERROR)

答案 1 :(得分:0)

好的,感谢@djangozone让我开始朝着正确的方向前进,我想出了一个解决方案。我的问题开始是因为我认为因为在DRF之外调用server_error,所以它会限制我使用DRF功能来提供格式正确的响应的能力。还有一些工作要做,以便让DRF正确渲染它。这是:

from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.settings import api_settings
from rest_framework import status
import re

def get_format_suffix(request):

    suffix_pattern = r'\.([a-z0-9]+)$'
    match = re.search(suffix_pattern, request.path)
    format = match and match.group(1)

    return format

def api_server_error(request, template_name=None):

    drf_request = Request(request)
    format_suffix = get_format_suffix(drf_request)
    accepted_renderer = drf_request.negotiator.select_renderer(
        drf_request, [renderer() for renderer in api_settings.DEFAULT_RENDERER_CLASSES], format_suffix=format_suffix
    )

    response = Response({'detail' : "Internal server error"}, status = status.HTTP_500_INTERNAL_SERVER_ERROR)
    response.accepted_renderer = accepted_renderer[0]
    response.accepted_media_type = response.accepted_renderer.media_type
    response.renderer_context = {'request': drf_request}
    response.render()

    return response