【问题标题】:How do I write a requested JSON array to a CSV file in Python?如何在 Python 中将请求的 JSON 数组写入 CSV 文件?
【发布时间】: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


    【解决方案1】:

    您的函数中间有 return 语句,该语句终止了进一步的执行(任何超出的内容永远不会到达),尝试将其移至结束,如果您使用 .close,也不要使用 .close...(它确实为您处理关闭)即:

    @app.route('/form/get_score', methods=['POST'])
    def get_score():
       req = request.get_json()
       print(req)
       res = make_response(jsonify(req), 200)
       with open('/userinfo/scores.csv', 'a', newline='') as File:
          writer = csv.writer(File)
          writer.writerow(req)
       return res
    

    【讨论】:

    • 好建议,但是当我这样做时,我收到响应状态为 500,而不是 200 的错误。您知道可能导致这种情况的原因吗?
    • @Sylens 仅从状态码很难说,如果可能的话检查 Flask 的日志
    • 我从那里弄明白了。我必须将 BASE_DIR 添加到 /userinfo/scores.csv 并且“newLine =”无效。现在可以了。非常感谢!
    • @Sylens 我将newLine 编辑为newline 以避免更多读者的潜在混淆,我保留了路径,因为这是特定于机器的。
    猜你喜欢
    • 2021-05-25
    • 2013-02-03
    • 2021-08-15
    • 2019-01-29
    • 2021-09-05
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多