0

I'm new with django-piston and whenever i get/post data to xml, the xml's element is always and < resource >

<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>

is there a way to change it in the handlers.py? i just want to chage the resource to product and if it possible, can i also put an id to the xml element?

gadss
  • 21,687
  • 41
  • 104
  • 154

2 Answers2

2

You have to write your own XMLEmitter. Here's one that always uses the tag product instead of resource.

Making it intelligent requires a bit more work, since models are serialized into dicts in Emitter.construct() method and it's impossible to extend properly. It would be nice to know the original model class in the _to_xml() method and name the element based on the class name.

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')

Also, you may want to look at PBS Education's django-piston fork at https://github.com/pbs-education/django-piston. It allows you to customize the output in other ways with PistonViews.

Visa Kopu
  • 695
  • 3
  • 7
  • 20
  • I use PistonViews from PBS (actually, I stripped the PistonView code, add it as a separate module, and use vanilla Piston. ) Piston Views are pretty awesome and it would be nice to see them merged back into Piston core. – Joe J Jan 31 '13 at 07:24
0

Elementtree will help you. You can change whatever you want to change, Read the file, parse it using elementree and update the values and again put it to the file (if needed).

Tauquir
  • 6,613
  • 7
  • 37
  • 48