Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

javascript - How to serve a csv file or retrieve csv data from a Flask server using fetch calls?

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...