1

我正在使用Django 2.xDRF

我有一个视图,它以不同的格式返回二进制数据,如pdf,eps等。

要返回二进制响应,我设置了renderer_classes属性,我的观点是

class DownloadQRCode(APIView):
    renderer_classes = (PdfFileRenderer, EPSRenderer,)

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)

        name = serializer.validated_data.get('name')
        data = serializer.validated_data.get('data')

        mimetype = None

        if data and name:

            imgarr = name.rsplit('.', 1)

            if len(imgarr) == 2:
                name, format = imgarr

                if format == 'pdf':
                    data = str(unquote(data, encoding='utf-8'))
                    data, mimetype = generate_data_cairo(data, format)
                if format == 'eps':
                    data = str(unquote(data, encoding='utf-8'))
                    data, mimetype = svg_2_eps(data)

                if data and mimetype:

                    response = Response(data=data, content_type=mimetype)

                    response['Content-Disposition'] = 'attachment; filename=%s' % "-".join(name.split())

                    return response
                else:
                    return Response(status=status.HTTP_400_BAD_REQUEST, data='Either data or mime type was missing')
            else:
                return Response(status=status.HTTP_400_BAD_REQUEST, data='filename does not contain formatInfo')
        else:
            return Response(status=status.HTTP_400_BAD_REQUEST)

我有两个renderer_classes

PdfFileRenderer

class PdfFileRenderer(BaseRenderer):
    media_type = 'application/octet-stream'
    format = None
    charset = None
    render_style = 'binary'

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

EPSRenderer

class EPSRenderer(BaseRenderer):
    media_type = 'image/eps'
    format = None
    charset = 'utf-8'
    render_style = 'binary'

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

对于该文件类型,使用其中任何一个都可以正常工作。但我想同时使用两者,以便可以根据请求的文件使用适当的渲染器。

但是,这会产生错误,并且只有集合中的第一个有效。

4

1 回答 1

0

同意@Nafees

通过覆盖get_renderer()方法解决了它。

def get_renderer(self):

    imgarr = name.rsplit('.', 1)
    name, format = imgarr

    if format == 'pdf':
       return [BinaryRenderer()]
    if format == 'eps':
       return [EPSRenderer()]

    return super().get_renderer()
于 2019-11-15T12:12:55.140 回答