Flask restful output XML only

本小妞迷上赌 提交于 2021-01-29 18:07:50

问题


I am new to experimenting with creating API's and I was interested to make an app that returns data in an XML format only on the API post request.

The flask-restful code below is just a glorified version of how to do an XML response from the git repo examples to view.

from simplexml import dumps
from flask import make_response, Flask
from flask_restful import Api, Resource

def output_xml(data, code, headers=None):
    """Makes a Flask response with a XML encoded body"""
    resp = make_response(dumps({'response' :data}), code)
    resp.headers.extend(headers or {})
    return resp


tou = [{
    "startTime": "2:00PM",
    "duration": "6 Hours",
    "numberOfIntervals" : 3,
    "intervalDuration" : "1 hour,4 hour,1 hour",
    "typicalIntervalValues" : "$0.50,$0.75,$0.50"
}]



app = Flask(__name__)
api = Api(app, default_mediatype='application/xml')
api.representations['application/xml'] = output_xml


class call(Resource):
    def post(self):
        callInfo = {"notification" : "True",
                "startTime" : "2:00PM",
                "duration" : "6 Hours",
                "randomization": "None",
                "rampUp" : "None",
                "recovery" : "None",
                "numberOfSignals" : "2",
                 "signalNameSimple" : [{
                    "signalType" : "level",
                    "units" : "None",
                    "numberOfIntervals" : "None",
                    "intervalDuration" : "None",
                    "typicalIntervalValues" : "1,2,1",
                    "signalTarget" : "None"}],
                 "signalNameElectricityPrice" : [{
                    "signalType" : "price",
                    "units" : "USD per kWh",
                    "numberOfIntervals" : "3",
                    "intervalDuration" : "1 hour,4 hour,1 hour",
                    "typicalIntervalValues" : "$0.50,$0.75,$0.50",
                    "signalTarget" : "None"}]
                        }
        return callInfo



api.add_resource(call, '/api/v1/cpp/scenario/three')


if __name__ == '__main__':
    app.run(debug=False)

The problem that I have (maybe this isnt even a problem) is the Flask-restful app will only return an XML response if its defined in the requests header, else it returns a JSON response. For example in the code below if I dont have the headers={'Accept': 'application/xml'} this script will error because the Flask-restful app response is JSON format.

import requests
import xml
from xml.etree import ElementTree


response = requests.post("http://127.0.0.1:5000/api/v1/cpp/scenario/three", headers={'Accept': 'application/xml'})
#response = requests.post("http://127.0.0.1:5000/api/v1/cpp/scenario/three")


root = ElementTree.fromstring(response.content)
for child in root.iter('*'):
    print(child.tag)

QUESTION, how could I modify my Flask App that it only returns XML? If this seems like a silly question could someone elaborate more on why an API would need JSON and XML? The real world scenario I am hoping to learn on how to implement this only uses XML only, and I am worried that having this extra headers={'Accept': 'application/xml'} will create a problem as the devices communicating to the API are just "machines" not people with custom python coding abilities. If someone could help me understand what is typical to the API industry maybe that would help a little bit too :)

来源:https://stackoverflow.com/questions/64573932/flask-restful-output-xml-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!