【发布时间】:2021-05-31 14:13:10
【问题描述】:
我是编程新手,我正在尝试保存我的数据,但我无法弄清楚。我正在为一个科学实验建立一个网站,在一个页面上,用户单击“是”或“否”按钮来说明他们是否识别所显示的图像。他们必须这样做 25 次。我有 javascript 生成一个包含 25 个“是”或“否”项目的数组,并且是该人进行分析的时间的 25 倍。然后将此信息传递给烧瓶 python,它应该被保存在那里。我设法在服务器上打印数组,但无法在我的 CSV 文件中获取它。
数组可能如下所示:
['"Y"', '"N"', '"Y"', '"Y"', '"Y"', '"Y"', '"Y"', '"Y"', '"Y"', '"Y"', '"Y"', '"Y"', '"N"', '"Y"', '"Y"', '"Y"', '"N"', '"N"', '"Y"', '"Y"', '"Y"', '"Y"', '"Y"', '"Y"', '"N"', 746, 1384, 278, 172, 764, 270, 306, 306, 698, 172, 956, 1204, 426, 702, 752, 716, 596, 719, 724, 972, 275, 366, 930, 383, 672]
发送数组的 javascript 如下所示:
function finishIt() { // combines arrays and sends user to 'thank you' page
if (array2.length == 0) {
var finalResults = results.concat(duration);
fetch(`${window.origin}{{ url_for('get_score') }}`, {
method: "POST",
credentials: "include",
body: JSON.stringify(finalResults),
cache: "no-cache",
headers: new Headers({
"content-type" : "application/json"
})
})
.then(function (response){
if (response.status !== 200) {
console.log(`Response status was not 200: ${response.status}`);
return ;
}
response.json().then(function (data){
//console.log(data)
})
})
// location.href = '{{ url_for('thankyou') }}';
}
}
接收并尝试保存数据的python函数如下所示:
@app.route('/form/get_score', methods=['POST'])
def get_score():
req = request.get_json()
print(req)
res = make_response(jsonify(req), 200)
return res
with open('/userinfo/scores.csv', 'a', newLine='') as File:
writer = csv.writer(File)
writer.writerow(req)
File.close()
print(req) 确实将数组正确打印到 pythonanywhere 服务器,但我不知道如何保存它。任何帮助将不胜感激!
【问题讨论】:
标签: javascript python arrays json flask