gpt4 book ai didi

python - 在 Flask 中从 AngularJS 接收 JSON

转载 作者:太空宇宙 更新时间:2023-11-04 10:36:34 24 4
gpt4 key购买 nike

我有一个 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 -

对于任何好奇的人,request.jsonNone 当我得到 HTTP PUT...

问题

我怎样才能正确接收 AngularJS 发送到 flask 的内容? ?


HTTP PUT 的 Wireshark 转储:

这是来自 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
);

最佳答案

您为 JSON 使用了错误的 mimetype。而不是 application/x-www-form-urlencoded,它应该是 application/json

关于python - 在 Flask 中从 AngularJS 接收 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23020030/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com