我正在编写一个python-flask api来使用xml解析和操作xml来进行dict。以下是我的初始代码:
from flask import Flask, jsonify, abort, make_response, request,
render_template
import sys, sqlite3, requests, datetime, time, re, json, optparse
import xmltodict
import helpers
import platform
app = Flask(__name__)
start = int(round(time.time()))
print("api running")
@app.route("/", methods=['GET', 'POST'])
def parse_xml():
content_dict = xmltodict.parse(request.data)
return content_dict
if __name__ == '__main__':
print("Starting python app")
app.run(host='0.0.0.0', port=8080, debug=False)
以下卷曲请求:curl -H "Authorization: Bearer Token" -X POST -d '<xml><From>Jack</From><Body>Hello, it worked!</Body></xml>' url
返回错误:
2018-04-18T13:33:38.831293275Z [2018-04-18 13:33:38,830] app中的错误: / [POST] 2018-04-18T13:33:38.831324305Z Traceback(大多数 最近呼叫最后):2018-04-18T13:33:38.831331225Z文件 “/usr/lib/python2.7/site-packages/flask/app.py”,1982年,在 wsgi_app 2018-04-18T13:33:38.831336961Z response = self.full_dispatch_request()2018-04-18T13:33:38.83134283Z文件 “/usr/lib/python2.7/site-packages/flask/app.py”,第1614行, full_dispatch_request 2018-04-18T13:33:38.831352063Z rv = self.handle_user_exception(e)2018-04-18T13:33:38.831357531Z文件 “/usr/lib/python2.7/site-packages/flask/app.py”,第1517行,in handle_user_exception 2018-04-18T13:33:38.83136302Z
再加(exc_type,exc_value,tb)2018-04-18T13:33:38.831367481Z文件 “/usr/lib/python2.7/site-packages/flask/app.py”,第1612行, full_dispatch_request 2018-04-18T13:33:38.831372038Z rv = self.dispatch_request()2018-04-18T13:33:38.831377673Z文件 “/usr/lib/python2.7/site-packages/flask/app.py”,第1598行, dispatch_request 2018-04-18T13:33:38.831385927Z返回 self.view_functionsrule.endpoint 2018-04-18T13:33:38.831391913Z文件“/src/simpleapp.py”,第14行,in parse_xml 2018-04-18T13:33:38.831396571Z content_dict = xmltodict.parse(request.data)2018-04-18T13:33:38.831401027Z文件 “/usr/lib/python2.7/site-packages/xmltodict.py”,第330行,解析 2018-04-18T13:33:38.831407166Z parser.Parse(xml_input,True) 2018-04-18T13:33:38.831412259Z ExpatError:找不到元素:第1行, 第0栏2018-04-18T13:33:38.831705887Z 100.96.2.171 - - [18 / Apr / 2018 13:33:38]“POST / HTTP / 1.1”500 -
任何帮助将不胜感激,谢谢。
答案 0 :(得分:0)
您必须将您的curl请求更改为key = value对,以便于处理。
卷曲:
curl -H "Authorization: Bearer Token" -X POST -d 'SomeKey=<xml><From>Jack</From><Body>Hello, it worked!</Body></xml>' http://127.0.0.1:5000
的Python:
from flask import Flask, jsonify, request
import xmltodict
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def parse_xml():
xml_data = request.form['SomeKey']
content_dict = xmltodict.parse(xml_data)
return jsonify(content_dict)
响应:
{
"xml": {
"Body": "Hello, it worked!",
"From": "Jack"
}
}
答案 1 :(得分:0)
您还可以将curl用于post
XML文件内容:
curl -X POST -d @data.xml -H 'Accept: application/xml' -H 'Content-Type: application/xml' url
data.xml
内容:
<xml>
<From>Jack</From>
<Body>Hello, it worked!</Body>
</xml>