django rest框架 - 自定义渲染器

时间:2013-12-31 03:41:42

标签: python django django-rest-framework

我正在尝试调整现有的XMLRenderer来创建自定义的XMLRenderer -

class CustomRenderer(renderers.BaseRenderer):
    """
    Renderer which serializes to CustomXML.
    """

    media_type = 'application/xml'
    format = 'xml'
    charset = 'utf-8'

    def render(self, data, accepted_media_type=None, renderer_context=None):
        """
        Renders *obj* into serialized XML.
        """
        if data is None:
            return ''

        stream = StringIO()

        xml = SimplerXMLGenerator(stream, self.charset)
        xml.startDocument()
        xml.startElement("job id='string1'", {})

        self._to_xml(xml, data)

        xml.endElement("job")
        xml.endDocument()
        return stream.getvalue()

    def _to_xml(self, xml, data):
        if isinstance(data, (list, tuple)):
            for item in data:
                xml.startElement("string2", {})
                self._to_xml(xml, item)
                xml.endElement("string2")

        elif isinstance(data, dict):
            for key, value in six.iteritems(data):
                xml.startElement(key, {})
                self._to_xml(xml, value)
                xml.endElement(key)

        elif data is None:
            # Don't output any value
            pass

        else:
            xml.characters(smart_text(data))

对于string1,我希望它从调用它的视图中获取值。 string1 = API中GET的主键。

即。如果我正在呼叫http://localhost/API/2345 then string1 = 2345

对于string2,我希望它返回类似于他们在以下帖子中所做的模型名称 -

Adding root element to json response (django-rest-framework)

这是自定义呈现器返回的值,以便可以将JSON / XML的根值设置为模型名称。

我已经尝试调整CustomRenderer以包含行但是在运行我的视图时它抱怨我的views.py上的“object()没有参数” -

if request.method == 'GET':
    DEV = Trgjob.objects.using('database1').filter(job_id=pk).order_by('job_order')
    serializer = CustomSerializer(DEV, many=True)
    return CustomRenderer(serializer.data)

1 个答案:

答案 0 :(得分:1)

看起来你正试图从视图中返回渲染器实例? 您应该只从视图返回常规数据,但使用视图类上的renderer_classes属性设置渲染器类。

class MyView(APIView):
    renderer_classes = [CustomRenderer]

    ...

    def get(self, request, pk=None):
        DEV = Trgjob.objects.using('database1').filter(job_id=pk).order_by('job_order')
        serializer = CustomSerializer(DEV, many=True)
        return Response(serializer.data)

修改:至于从视图中为渲染器添加额外的上下文...您可以通过检查renderer_context['view']来做到这一点,所以render()中的这些内容就是这样的方法...

view = renderer_context['view']
job_id = view.kwargs['job_id']