【问题标题】:How to create XML endpoint in Flask?如何在 Flask 中创建 XML 端点?
【发布时间】:2015-03-13 00:54:18
【问题描述】:

我在 SQLAlchemy 中有以下属性:

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

对于JSON,我只是使用jsonify(),对于XML,我该怎么做?

【问题讨论】:

    标签: python xml python-2.7 flask


    【解决方案1】:

    所有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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-12
      • 2014-05-07
      • 1970-01-01
      • 2022-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多