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

0

Issue

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!

Solution

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) i.e.:

@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

Answered By – Daweo

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More