我在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
所做的只是转储传递给它的参数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')