gpt4 book ai didi

python - 如何在 Flask 中创建 XML 端点?

转载 作者:太空宇宙 更新时间:2023-11-03 15:09:16 25 4
gpt4 key购买 nike

我在 SQLAlchemy 中有以下属性:

@property
def serialize(self):
return {
'name' : self.name,
'description' : self.description,
'id' : self.id,
'price' : self.price,
'course' : self.course,
}

对于 JSON,我只是使用了 jsonify(),对于 XML 我该如何做呢?

最佳答案

所有jsonify都是doing正在转储使用 json 传递给它的参数,并将响应的内容类型设置为 application/json。您将为 XML 执行完全相同的操作:转储数据(Python 具有内置的 etree 库或更强大的 lxml )并将内容类型设置为 application/xml .

有许多方法可以使用 XML 表示数据,所以这取决于您,但基本概要是:

import xml.etree.ElementTree as ET
root = ET.Element('root') # name the root whatever you want
# add your data to the root node in the format you want
return app.response_class(ET.tostring(root), mimetype='application/xml')

关于python - 如何在 Flask 中创建 XML 端点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29023035/

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