如何进行二进制资源的内容协商

时间:2019-03-05 14:32:25

标签: django-rest-framework

我有一个端点X,它像超级按钮一样散出json。可以将相同的资源生成为二进制变量。 X的终结点由视图集构成,X的二进制版本在动作装饰器的帮助下具有自己的终结点。

class XViewSet(ReadOnlyModelViewSet):
    queryset = X.objects.all()
    serializer_class = XSerializer

    @action(detail=True, methods=['get'])
    def binary(self, request, pk=None):
        x = self.get_object()
        binx = x.get_binary(FORMAT)
        ..

很显然,binary永远不会吐出json。我如何掌握协商的格式,如何将binary支持的二进制格式告诉django-rest-framework?

1 个答案:

答案 0 :(得分:1)

您不应该从ViewSet返回二进制数据,而要用custom renderer进行转换:

from rest_framework.renderers import BaseRenderer, JSONRenderer

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

    def render(self, data, media_type=None, renderer_context=None):
        # Either use `data` or access the view via
        # the `renderer_context` 
        view = renderer_context['view']
        return view.get_object().get_binary()

class XViewSet(ReadOnlyModelViewSet):
    queryset = X.objects.all()
    serializer_class = XSerializer
    renderer_classes = (JSONRenderer, BinaryRenderer)

查看how the renderer is determined上的文档。