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

1 投票
1 回答
1666 浏览
提问于 2025-04-16 14:33

我想在谷歌的应用引擎上部署一个网络服务。我选择了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的新手,希望能得到帮助。

Hariharan

1 个回答

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。

撰写回答