gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:53:49 24 4
gpt4 key购买 nike

我的目的是在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com