我们来看看这个样本:
url(r'^test[/]$', test_handler, { 'emitter_format': 'xml' }),
使用以下处理程序:
class testHandler(BaseHandler):
allowed_methods = ('GET',)
def read(self, request):
return {'element': 'I want to be first', 'test': 'No way', }
调用API时的结果是:
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>
我不想在第一时间获得'No way',那么如何在返回的元素上定义订单优先级?
答案 0 :(得分:0)
我通过创建自己的发射器找到答案:
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',))
并以这种方式返回嵌套的元素:
return [{'element': 'I want to be first'}, {'test': 'No way', }]