在Flask中接收AngularJS的JSON
我有一个AngularJS的应用,它通过HTTP PUT
把数据发送到flask;我可以看到数据正确地到达了服务器……但是,不知道为什么,当Angular向服务器发送HTTP PUT
请求时,我的flask方法却无法读取这些数据……
Flask代码:
@app.route('/api/thing/hostform', methods=['GET'])
@login_required
def get_blank_host_row():
retval = [host_row(host_name="RANDOM_HOST")]
return Response(dumps(retval), mimetype='application/json')
@app.route('/api/thing/hostform', methods=['PUT'])
@login_required
def append_blank_host_row():
retval = request.form.get('hosts', "!! ERROR !!")
print "PUT RESULT", retval
retval.append(host_row())
return Response(dumps(retval), mimetype='application/json')
“formsubmit_add2”能够正确地从/api/thing/hostform
获取数据;但是,不知道为什么request.form.get('hosts', "!! ERROR !!")
总是出现HTTP 500错误,具体情况如下……
10.93.10.120 - - [11/Apr/2014 13:15:22] "GET /formsubmit_add2 HTTP/1.1" 200 -
10.93.10.120 - - [11/Apr/2014 13:15:22] "GET /api/thing/hostform HTTP/1.1" 200 -
PUT RESULT !! ERROR !!
10.93.10.120 - - [11/Apr/2014 13:15:25] "PUT /api/thing/hostform HTTP/1.1" 500 -
对于好奇的人来说,当我收到HTTP PUT
请求时,request.json
是None
……
问题
我该如何正确接收AngularJS发送到flask的数据呢?
Wireshark抓取的HTTP PUT数据:
这是从AngularJS发送的HTTP PUT
请求的wireshark抓取数据……
Hypertext Transfer Protocol
PUT /api/thing/hostform HTTP/1.1\r\n
[Expert Info (Chat/Sequence): PUT /api/thing/hostform HTTP/1.1\r\n]
[Message: PUT /api/thing/hostform HTTP/1.1\r\n]
[Severity level: Chat]
[Group: Sequence]
Request Method: PUT
Request URI: /api/thing/hostform
Request Version: HTTP/1.1
Host: tsunami:5000\r\n
User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:28.0) Gecko/20100101 Firefox/28.0\r\n
Accept: application/json, text/plain, */*\r\n
Accept-Language: en-US,en;q=0.5\r\n
Accept-Encoding: gzip, deflate\r\n
Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n
Referer: http://server_name:5000/formsubmit_add2\r\n
Content-Length: 164\r\n
[Content length: 164]
Connection: keep-alive\r\n
\r\n
[Full request URI: http://server_name:5000/api/thing/hostform]
Line-based text data: application/x-www-form-urlencoded
{"hosts":[{"real_ip_addr":"","switch_port":"","host_nic_role":"Console",
"host_name":"RANDOM_HOST","host_nic_name":"","switch_name":"",
"altn_ip_addr":"192.0.2.42"}]}
AngularJS $http PUT:
$scope.add_row = function (data) {
// build an ajax request with $scope.data
var send = $http({
method : "PUT",
url : "/api/thing/hostform",
headers : {"Content-Type":
"application/x-www-form-urlencoded; charset=UTF-8"},
data: {"hosts": data},
});
send.success(
// something irrelevant here
);
2 个回答
1
来自Flask的Request
类文档:
json
如果内容类型是application/json,那么这里会包含解析后的JSON数据。否则,这里会是None。
应该使用get_json()方法来获取数据。
我觉得你的问题可能是因为request.form里没有hosts
这个键(可能有其他的键),因为你的内容类型不是json(application/json)。
为了给出更准确的答案,请告诉我request.form
里到底有什么?
3
你使用的JSON的类型不对。应该用application/json
,而不是application/x-www-form-urlencoded
。