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

标签 python xml web-services cherrypy

我的目的是在 Google App Engine 中部署网络服务。我使用 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初学者。请帮助我。

哈里哈兰

最佳答案

我也有类似的问题。我的解决方案是使用 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

关于python - Cherry Py - 在 Python 中以 XML 形式返回输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5456195/

相关文章:

linux系统发布WebService服务器故障

python - 如何对数据框中的 groupby 行应用计算并将结果 append 到数据框的底部?

python - 使用 python 3 的 Twitter 流 API

python - Eventlet 和锁定

python - 在Python ElementTree中,如何获取树中元素的所有祖先的列表?

java - WSDServiceFactory 中的空指针异常 - Apache CXF 库

python - 在 Python 2 中安全导入具有 Unicode 名称的模块

mysql - 如何在sql server中提取xml值字段(mysql中的extractvalue函数)

xml - 将数据从 XML 文件导入 R

java - Spring-ws XML 炸弹保护,有人知道吗?