【问题标题】:how to change xml element name in django-piston?如何更改 django-piston 中的 xml 元素名称?
【发布时间】:2011-12-02 05:59:46
【问题描述】:

我是 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 吗?

【问题讨论】:

    标签: python xml django django-piston


    【解决方案1】:

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

    让它变得智能需要更多的工作,因为模型在Emitter.construct() 方法中被序列化为dicts,并且不可能正确扩展。如果知道 _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')
    

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

    【讨论】:

    • 我使用来自 PBS 的 PistonViews(实际上,我剥离了 PistonView 代码,将其添加为单独的模块,并使用 vanilla Piston。)活塞视图非常棒,很高兴看到它们合并回来进入活塞芯。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      • 1970-01-01
      • 2017-12-27
      • 1970-01-01
      • 2010-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多