我刚开始尝试创建API,我很想制作一个仅在API发布请求后才返回XML格式数据的应用。
下面的烧瓶相关代码只是如何制作XML response from the git repo示例以进行查看的美化版本。
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)
我遇到的问题(也许这甚至不是问题)是Flask-restful应用程序仅在请求标头中定义了XML响应,否则返回JSON响应。例如,在下面的代码中,如果我没有headers={'Accept': 'application/xml'}
,则此脚本将出错,因为Flask-restful应用程序响应为JSON格式。
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)
问题 ,如何修改仅返回XML的Flask App?如果这是一个愚蠢的问题,有人可以详细说明吗API为什么需要JSON和XML?我希望学习如何仅使用XML来实现的现实场景,并且我担心拥有多余的headers={'Accept': 'application/xml'}
会造成问题,因为与API通信的设备只是“机器”,而不是人具有自定义的python编码功能。如果有人可以帮助我了解API行业的典型特征,那也可能会有所帮助:)