Python Flask:单击按钮下载 csv 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30024948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Flask: Download a csv file on clicking a button
提问by Tarun Dugar
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:
我刚开始使用 Flask/Python。我想要实现的是我的 HTML 中有一个下载按钮,它调用以下函数:
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?
我面临的问题是我找不到下载此 csv 文件或将其作为 JSON 字符串返回的方法,因此我可以使用 Javascript 下载它。知道如何将其作为 JSON 发送或通过 Flask 本身下载吗?最好的方法是什么?
采纳答案by Rob?
Here is one way to download a CSV file with no Javascript:
这是一种无需 Javascript 即可下载 CSV 文件的方法:
#!/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)
回答by wanderlust
Firstly you need to import from flask make_response
, that will generate your response and create variable, something like response
.
Secondly, make response.content_type = "text/csv"
Thirdly - return your response.
首先,您需要从 flask 导入make_response
,这将生成您的响应并创建变量,例如response
. 其次,使response.content_type = "text/csv"
第三 - 返回您的回复。
回答by kay - SE is evil
You can use flask.send_file()
to send a static file:
您可以使用flask.send_file()
发送静态文件:
from flask import send_file
@app.route('/getPlotCSV') # this is a job for GET, not POST
def plot_csv():
return send_file('outputs/Adjacency.csv',
mimetype='text/csv',
attachment_filename='Adjacency.csv',
as_attachment=True)