Django Piston : Define the priority of the returned elements
Let's take this sample :
url(r'^test[/]$', test_handler, { 'emitter_format': 'xml' }),
With the following handler :
class testHandler(BaseHandler):
allowed_metho开发者_高级运维ds = ('GET',)
def read(self, request):
return {'element': 'I want to be first', 'test': 'No way', }
The result when calling the API will be :
Content-Type: text/xml; charset=utf-8
<?xml version="1.0" encoding="utf-8"?>
<response><test>No way</test><element>I want to be first</element></response>
I don't want to get the 'No way' in first place, so how to define an order priority on the elements returned ?
I found an answer by creating my own Emitter :
class CustomXmlEmitter(Emitter):
def _to_xml(self, xml, data):
if isinstance(data, (list, tuple)):
for item in data:
self._to_xml(xml, item)
elif isinstance(data, dict):
for key, value in data.iteritems():
xml.startElement(key, {})
self._to_xml(xml, value)
xml.endElement(key)
else:
xml.characters(smart_unicode(data))
def render(self, request):
stream = StringIO.StringIO()
xml = SimplerXMLGenerator(stream, "utf-8")
xml.startDocument()
xml.startElement("response", {})
self._to_xml(xml, self.construct())
xml.endElement("response")
xml.endDocument()
return stream.getvalue()
Emitter.register('custom_xml', CustomXmlEmitter, 'text/xml; charset=utf-8')
Mimer.register(lambda *a: None, ('text/xml',))
and return the element nested this way :
return [{'element': 'I want to be first'}, {'test': 'No way', }]
精彩评论