0

我是 django-piston 的新手,每当我将数据获取/发布到 xml 时,xml 的元素总是和 <资源>

<response>
<resource>
 <resource>4</resource>
 <resource>0</resource>
 <resource>2011-11-30</resource>
</resource>
<resource>
 <resource>4</resource>
 <resource>4</resource>
 <resource>2011-12-01</resource>
</resource>
<resource>
 <resource>4</resource>
 <resource>0</resource>
 <resource>2011-12-02</resource>
</resource>
<resource>
 <resource>4</resource>
 <resource>0</resource>
 <resource>2011-12-03</resource>
</resource>
<resource>
 <resource>4</resource>
 <resource>0</resource>
 <resource>2011-12-04</resource>
</resource>
</response>

有没有办法在 handlers.py 中改变它?我只想将资源转换为产品,如果可能的话,我还可以在 xml 元素中添加一个 id 吗?

4

2 回答 2

2

您必须编写自己的 XMLEmitter。这是一个始终使用标签product而不是resource.

让它变得智能需要更多的工作,因为模型在方法中被序列化为 dictsEmitter.construct()并且不可能正确扩展。最好知道_to_xml()方法中的原始模型类并根据类名命名元素。

from piston.emitters import Emitter, XMLEmitter

class ProductXMLEmitter(XMLEmitter):
    def _to_xml(self, xml, data):
        if isinstance(data, (list, tuple)):
            for item in data:
                attrs = {}
                # if item contains id value, use it as an attribute instead
                if isinstance(item, dict):
                    attrs["id"] = unicode(item.pop("id"))
                xml.startElement("product", attrs)
                self._to_xml(xml, item)
                xml.endElement("product")
        else:
            super(BetterXMLEmitter, self)._to_xml(xml, data)

# replace default XMLEmitter with ours
Emitter.register('xml', ProductXMLEmitter, 'text/xml; charset=utf-8')

此外,您可能想在https://github.com/pbs-education/django-piston上查看 PBS Education 的 django-piston fork 。它允许您使用 PistonViews 以其他方式自定义输出。

于 2011-12-02T07:53:36.297 回答
0

Elementtree将为您提供帮助。您可以更改您想要更改的任何内容,读取文件,使用 elementree 解析它并更新值并再次将其放入文件(如果需要)。

于 2011-12-02T07:27:24.907 回答