Django休息框架 - 将结果解析为tsv

时间:2013-02-01 18:39:18

标签: django rest django-views django-rest-framework

class TestAPI(APIView):   
    def post(self, request, format=None):
        # Here, I process the request in SomeClass method
        # 'some_result' is a tuple in the format below
        some_result = SomeClass.some_method(request)
        response = Response(some_result, status=status.HTTP_200_OK, headers=None)
        return response

仅供参考,'some_result'包含:

(u'text1', [('dataA1', 'dataA2', 'dataA3'), ('dataB1', 'dataB2', 'dataB3')], 'text2')

所以我的问题是,是否有可能解析这个元组(上图)所以我可以返回这样的tsv:

dataA1 dataA2 dataA3
dataB1 dataB2 dataB3

非常感谢提前。

1 个答案:

答案 0 :(得分:3)

查看有关实现自定义渲染器的文档。

http://django-rest-framework.org/api-guide/renderers.html#custom-renderers

自定义渲染器看起来像这样......

class TSVRenderer(renderers.BaseRenderer):
    media_type = 'text/tsv'
    format = 'tsv'

    def render(self, data, media_type=None, renderer_context=None):
        return ...  # TODO: Convert you incoming data representation into a TSV string

然后,您可以通过设置renderer_classes属性...

将渲染器添加到视图中
class TestAPI(APIView):
    renderer_classes = [TSVRenderer]
    ...