how to change xml element name in django-piston?

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?

Answers


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.


Need Your Help

Dynamic form fields in Symfony 1.4

php symfony-1.4 symfony-forms

I'm working on an e-commerce project and I got stuck at the cart update. Here I have to present a form using the contents of the current cart, with input fields containing the current quantities.

Update statement in sql server 2005

sql sql-server-2005 sql-update

Consider the following Dig, Assume that all the three tables have a column Is_Deleted by default it is set to 0... I want to update Is_Deleted=1 field of Customers table where CustId=2 only when th...