如何在 Flask 中创建 XML 端点?

Roy*_*Esh 3 python xml flask python-2.7

我在 SQLAlchemy 中有以下属性:

@property
def serialize(self):
    return {
        'name' : self.name,
        'description' : self.description,
        'id' : self.id,
        'price' : self.price,
        'course' : self.course,
    }
Run Code Online (Sandbox Code Playgroud)

对于 JSON,我刚刚使用了jsonify(),我该如何为 XML 做到这一点?

dav*_*ism 7

所有jsonify正在倾销传递给它的论点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')
Run Code Online (Sandbox Code Playgroud)