Search code examples
pythonxmlweb-servicescherrypy

Cherry Py - Return output as XML in Python


My intention is to deploy a web service in Google App Engine. I am using CherryPy as I found it very easy to understand.

import sys
sys.path.insert(0,'cherrypy.zip')

import cherrypy
from cherrypy import expose

class Converter:
    @expose
    def index(self):
        return "Hello World!"

    @expose
    def fahr_to_celc(self, degrees):
        temp = (float(degrees) - 32) * 5 / 9
        return "%.01f" % temp

    @expose
    def celc_to_fahr(self, degrees):
        temp = float(degrees) * 9 / 5 + 32
        return "%.01f" % temp

cherrypy.quickstart(Converter())

I would like to know, how to return the output in XML format, like

<?xml version="1.0" encoding="UTF-8"?> 
<root>
    <answer>Hello World!</answer>    
</root>

I am a beginner in Python. Kindly help me.

Hariharan


Solution

  • I had a similar issue. My solution was to use xml elementtree. It was something like

    ....
    #elementtree is stored in weird places... This catches most of em
    try:
        import xml.etree.ElementTree as ET # in python >=2.5
    except ImportError:
        try:
                import cElementTree as ET # effbot's C module
            except ImportError:
            try:
                import elementtree.ElementTree as ET # effbot's pure Python module
                except ImportError:
                        try:
                            import lxml.etree as ET # ElementTree API using libxml2
                        except ImportError:
                            import warnings
                            warnings.warn("could not import ElementTree "
                                    "(http://effbot.org/zone/element-index.htm)")
    
    def build_xml_tree(answer_txt=""):
        if not len(resources):
            return ""
        root = ET.Element("root")
        answer = ET.SubElement(root, "answer")
        answer.text = answer_txt
        xml_string = ET.tostring(root)
        return rxml_string
    

    Then call build_xml_tree from your function