[英]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.我正在尝试使用来自 JavaScript 前端的 fetch 调用,以便从用 Flask 编写的服务器/api 下载 csv 文件。 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.但是,在阅读之后,似乎没有当前的方法可以使用 fetch 调用下载 csv 文件,因此我尝试将 csv 文件数据转换为 json 以作为响应发送数据。 However, when I do a fetch call I get:但是,当我进行 fetch 调用时,我得到:
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:这是迄今为止我编写的 flask 服务器,其中涉及将 api 调用服务到 / 并将 csv 文件数据转换为 csv:FZ 文件数据到 api 调用
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 调用:
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任何帮助都会很棒
Have a look at send_from_directory in the official documentation.查看官方文档中的send_from_directory 。 It should help you if the only purpose is to fetch the csv from flask server.如果唯一的目的是从 flask 服务器获取 csv,它应该会对您有所帮助。 For any modifications to the csv you can continue to use pandas library.对于 csv 的任何修改,您可以继续使用 pandas 库。
@app.route('/uploads/<path:filename>')
def download_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename, as_attachment=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.