0

I'm trying to use a fetch call from a JavaScript front end in order to download a CSV file from a server/API written in Flask. But, after reading it seems like there's no current way to download a CSV file using fetch calls so instead I'm trying to convert CSV file data into JSON to be sent as the data instead in the response. However, when I do a fetch call I get:

SyntaxError: Unexpected token S in JSON at position 0

Here is the flask server I've written so far which involves servicing API calls to / and converting CSV file data into JSON:

from flask import Flask, request, send_file, jsonify
from flask_cors import CORS, cross_origin
import csv

app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

@app.route('/', methods=["GET"])
@cross_origin()
def transform_view():
    json_ = request.json
    new = pd.read_csv('grades.csv')
    json_vector = new.transform(json_)
    query = pd.DataFrame(json_vector)
    prediction = regr.predict(query)
    data = {'prediction': list({{prediction}})}
    return jsonify(data)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5001, debug=True)

And the fetch call:

fetch(
     "http://localhost:5001/",
     {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
    }
  ).then((response) => {
    // Check if the request is 200
    if (response.ok) {
      return response.json();
    }
}) 

Any help would be great

1 Answer 1

0

Have a look at send_from_directory in the official documentation. It should help you if the only purpose is to fetch the csv from flask server. For any modifications to the csv you can continue to use pandas library.

@app.route('/uploads/<path:filename>')
def download_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                           filename, as_attachment=True)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.