Flask:点击一个按钮下载一个csv文件 [英] Flask: Download a csv file on clicking a button
本文介绍了Flask:点击一个按钮下载一个csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$ b $ pre $函数downloadPlotCSV() {
$ .ajax({
url:/ getPlotCSV,
type:post,
success:function(data){
dataPlot = JSON。 parse(data);
console.log(dataPlot);
}
});
$ / code>
不完整的烧瓶代码是:
@ app.route('/ getPlotCSV',methods = ['POST'])
def plotCSV():
data = open(输出/ Adjacency.csv)
我遇到的问题是我无法找到下载这个csv文件或返回它作为一个JSON字符串,所以我可以下载它使用Javascript。任何想法如何我可以发送它为JSON或可能通过Flask本身下载?什么是最好的方法?
解决方案
这是下载不含Javascript的CSV文件的一种方法:
#!/ usr / bin / python
从瓶子导入瓶子,回应
app =瓶子(__ name__)
$ b $ hello():
return'''
< html>< body>
你好。 < a href =/ getPlotCSV>点击我。< / a>
< / body>< / html>
$'
@ app.route(/ getPlotCSV)
def getPlotCSV():
#打开(outputs / Adjacency.csv)作为fp:
#csv = fp.read()
csv ='1,2,3 \\\
4,5,6\\\
'
返回响应(
csv ,
mimetype =text / csv,
headers = {Content-disposition:
attachment; filename = myplot.csv})
app.run(debug = True)
I just got started with Flask/Python. What I want to achieve is that I have a download button in my HTML and it calls the following function:
function downloadPlotCSV() {
$.ajax({
url: "/getPlotCSV",
type: "post",
success: function(data) {
dataPlot = JSON.parse(data);
console.log(dataPlot);
}
});
}
The incomplete flask code is:
@app.route('/getPlotCSV', methods = ['POST'])
def plotCSV():
data = open("outputs/Adjacency.csv")
The problem I am facing is that I cannot find a way to download this csv file or return it as a JSON string so I can download it using Javascript. Any idea how I can send it as JSON or maybe download it via Flask itself? What's the best way?
解决方案
Here is one way to download a CSV file with no Javascript:
#!/usr/bin/python
from flask import Flask, Response
app = Flask(__name__)
@app.route("/")
def hello():
return '''
<html><body>
Hello. <a href="/getPlotCSV">Click me.</a>
</body></html>
'''
@app.route("/getPlotCSV")
def getPlotCSV():
# with open("outputs/Adjacency.csv") as fp:
# csv = fp.read()
csv = '1,2,3\n4,5,6\n'
return Response(
csv,
mimetype="text/csv",
headers={"Content-disposition":
"attachment; filename=myplot.csv"})
app.run(debug=True)
这篇关于Flask:点击一个按钮下载一个csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文