错误时返回不同的Content-Type响应

时间:2018-09-10 14:08:00

标签: django-rest-framework

使用一个渲染器给出一个端点:

class PNGRenderer(BaseRenderer):
    media_type = 'image/png'
    format = 'png'

    def render(self, data, media_type=None, renderer_context=None):
        return data

@renderer_classes((PNGRenderer, ))
def some_endpoint(request, format=None):
    filename = 'foo.png'
    if not os.path.exists(filename):
        raise NotFound("File not found")
    else:
        with open(filename, 'rb') as f:
            data = f.read()
            return response(data)

如果找不到application/json,我想返回foo.png。显然,在现实生活中,filename并不总是"foo.png",而是动态的。

即使向端点提供了format ='png',我如何返回json以便在响应中将Content-Type正确设置为application/json

1 个答案:

答案 0 :(得分:0)

在撰写问题时,我找到了更改渲染器的答案:Get-AzureADGroupMember

尤其是:

request.accepted_renderer = JSONRenderer()

我不确定这是否是处理 binary @renderer_classes((PNGRenderer, )) def some_endpoint(request, format=None): filename = 'foo.png' if not os.path.exists(filename): request.accepted_renderer = JSONRenderer() raise NotFound("File not found") else: with open(filename, 'rb') as f: data = f.read() return response(data) 的异常的正确方法。