Cherry Py - 在Python中以XML格式返回输出

时间:2011-03-28 08:07:31

标签: python xml web-services cherrypy

我的目的是在Google App Engine中部署Web服务。我使用CherryPy,因为我发现它很容易理解。

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

我想知道,如何以XML格式返回输出,比如

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

我是Python的初学者。请帮助我。

哈里哈兰

1 个答案:

答案 0 :(得分:3)

我有类似的问题。我的解决方案是使用xml elementtree。这就像

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

然后从你的函数中调用build_xml_tree