用jquery和flask发送数组数据 [英] Sending array data with jquery and flask
问题描述
$ b $
$。post(/ test)我需要将数据从一个html页面发送回我的Python应用程序。 ,{x:[1.0,2.0,3.0],y:[2.0,3.0,1.0]},function(dat){console.log(dat);});
在服务器上:
@ app.route('/ test',methods = ['POST'])
pre>
def test():
print request.form.keys()
打印dir(request.form)
打印request.form [x []]
返回jsonify({Mean:10.0})
很让我吃惊的是,这些键是
['y []','x []']
和
print request.form [x []]
结果为1.
有什么正确的方法可以做到这一点?
解决方案当发送包含数组或对象值的POST数据时,jQuery遵循 PHP的惯例添加括号的字段名称。这不是一个网络标准,但是因为PHP支持开箱即用,所以很受欢迎。
因此,正确处理POST数据和Flask列表正如你所发现的那样,确实要在方框中加上方括号。您可以使用 >
MultiDict.getlist()
:
请求。 form.getlist(x [])
$ b (request.form
是一个MultiDict
对象)。这会返回字符串,而不是数字。如果您知道这些值是数字,您可以通过getlist()
方法来转换它们:
request.form.getlist(x [],type = float)
如果您不希望应用其他方括号,请不要将数组用作值,或者将数据编码为JSON。您必须使用
jQuery.ajax()
而不是:
$。ajax({
url:/ test,
type:POST,
data:JSON.stringify({x:[1.0,2.0,3.0],y:[2.0,3.0,1.0]}),
contentType:application / json; charset = utf-8,
成功:函数(dat){console.log(dat);}
});
在服务器端,使用
request.get_json()
解析发布的数据: / p>
data = request.get_json()
x = data ['x']
这也处理数据类型转换。您将浮点数字作为JSON发布,Flask将在Python端重新将其解码为浮点值。
I need to send data from a html page back into my Python application:
$.post("/test", {x: [1.0,2.0,3.0], y: [2.0, 3.0, 1.0]}, function(dat) {console.log(dat);});
on the server:
@app.route('/test', methods=['POST']) def test(): print request.form.keys() print dir(request.form) print request.form["x[]"] return jsonify({"Mean": 10.0})
Much to my surprise the keys are
['y[]', 'x[]']
and
print request.form["x[]"]
results in 1.
What's the correct way to do this?
解决方案When sending POST data containing values that are arrays or objects, jQuery follows a PHP convention of adding brackets to the field names. It's not a web standard, but because PHP supports it out of the box it is popular.
As a result, the correct way of handling POST data with lists on the Flask side is indeed to append square brackets to the field names, as you discovered. You can retrieve all values of the list using
MultiDict.getlist()
:request.form.getlist("x[]")
(
request.form
is aMultiDict
object). This returns strings, not numbers. If you know the values to be numbers, you can tell thegetlist()
method to convert them for you:request.form.getlist("x[]", type=float)
If you don't want the additional brackets to be applied, don't use arrays as values, or encode your data to JSON instead. You'll have to use
jQuery.ajax()
instead though:$.ajax({ url: "/test", type: "POST", data: JSON.stringify({x: [1.0,2.0,3.0], y: [2.0, 3.0, 1.0]}), contentType: "application/json; charset=utf-8", success: function(dat) { console.log(dat); } });
and on the server side, use
request.get_json()
to parse the posted data:data = request.get_json() x = data['x']
This also takes care of handling the datatype conversions; you posted floating point numbers as JSON, and Flask will decode those back to float values again on the Python side.
这篇关于用jquery和flask发送数组数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!