我正在使用Django 2.x和DRF
我有一个视图,它以不同的格式返回二进制数据,如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
对于该文件类型,使用其中任何一个都可以正常工作。但我想同时使用两者,以便可以根据请求的文件使用适当的渲染器。
但是,这会产生错误,并且只有集合中的第一个有效。