简体   繁体   中英

How do I write a requested JSON array to a CSV file in Python?

I am new to programming and I'm trying to save my data but I cannot figure it out. I am building a website for a scientific experiment where on one page, users click 'yes' or 'no' buttons to say whether or not they recognize an image that is shown. They have to do this 25 times. I have javascript that generates an array with 25 'yes' or 'no' items and 25 times the time that the person took to anser. This information is then passed to flask python, where it is supposed to be saved. I manage to print the array on the server but I can't get it in my CSV file.

An array could look like this: ['"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]

The javascript that sends the array looks like this:

            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') }}';
            }
        }

The python function that receives and tries to save the data looks like this:

@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) does correctly print the array to the pythonanywhere server, but I don't know how to save it. Any help would be greatly appreciated!

You have return statement in middle of your function which terminates further execution (anything beyond is never reached), try moving it to end, also do not use .close if you use with open ... (it does handle closing for you) ie:

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM