Python3.6.1 :: Anaconda 4.4.0(64bit)+ Flask 0.12.2
我使用jQuery发布我的数据
$.ajax({
url:'/immutableTest',
data: {'key': kvs },
type: 'POST'
});
和typeof kvs is an object
(数组),里面有很多对象。所以当console.log(kvs)
得到
(3) [{…}, {…}, {…}]
0:{"status": "good", "color": "#414141", "describe": "The machine is running"}
1:{"status": "error", "color": "#ff0000", "describe": "Something error with it"}
2:{"status": "powerOff", "color": "#000000", "describe": "Closing"}
我的数据在后端看起来像
@main.route('/immutableTest', methods=['POST'])
def immutableTest():
for k, v in request.form.items():
print(k, v)
key[0][status] powerOff
key[0][color] #414141
key[0][describe] The machine is running
key[1][status] error
key[1][color] #ffff00
key[1][describe] Something error with it
key[2][status] powerOff
key[2][color] #000000
key[2][describe] Closing
所以我编写程序来提取我需要的键值。 我想重新编写以下代码。
@main.route('/immutableTest', methods=['POST'])
def immutableTest():
kvs=[]
kv={}
i=0
for kk, vv in request.form.items():
kv[kk.split('[')[2].replace(']', '')] = vv
if i == 2:
kvs.append(kv)
kv={}
i = 0
else:
i = i + 1
print(kvs)
# Script to Database to update...
return 'Update success.'
这将导致
[
{"status": "good", "color": "#414141", "describe": "The machine is running"},
{"status": "error", "color": "#ff0000", "describe": "Something error with it"},
{"status": "powerOff", "color": "#000000", "describe": "Closing"}
]
我需要结果,以便我可以轻松更新MongoDB中的数据。
答案 0 :(得分:2)
嗯,你必须定义什么' smart'意味着在你的背景下。如果您想要在JS前端和Python后端之间传输结构化数据的更易于管理且有些标准的方法,则可以使用JSON而不是将数据打包为POST结构。例如,在JS方面:
$.ajax({
url:'/immutableTest',
data: JSON.stringify(kvs),
contentType: "application/json",
type: 'POST'
});
然后在你的Flask应用程序中:
@main.route('/immutableTest', methods=['POST'])
def immutableTest():
kvs = request.get_json()
print(kvs)
它应该自动传输结构。