javascript - Flask - 获取要下载为 csv 的数据框
问题描述
单击按钮时,我想使用来自 html 中多个输入字段的值并将其用作参数来下载一些数据。然后我尝试将其转换为 csv 并将其下载为 csv 文件。我在 javascript 中发现响应包含 csv 格式的数据,但没有下载文件。我错过了什么?
.html 文件:
***html I left out to keep this short***
<input type="button" value="Download CSV" onclick="downloadacsfile()">
.js 文件:
function downloadacsfile() {
var acs_variable = document.getElementById('variableid').value;
var state = document.getElementById('stateselection').value;
var acs_type = document.getElementById('acs_type').value;
var year = document.getElementById('years').value;
$.get("/api/acs_download", {acs_variable: acs_variable, state:state, acs_type:acs_type, year:year }, function(response){
console.log(response.exist);
});
}
.py 文件:
app.add_url_rule('/api/acs_download', 'acs_download', acs_download, methods=['GET'])
def acs_download():
acs_variable = request.args['acs_variable']
state = request.args["state"]
acs_type = request.args["acs_type"]
year = request.args["year"]
params = {'acs_type': acs_type,
'year': year,
'variable': acs_variable,
'state': state}
###Gets data from 3rd party API to csv format###
datafetch = fetcher.Fetcher(api_key)
data = datafetch.get_census_data(**params)
data = data.to_csv(index=False)
return Response(
data,
mimetype="text/csv",
headers={"Content-disposition":
"attachment; filename=testfile.csv"})
解决方案
您需要用户重定向到要下载文件的位置。因此,您无需发出 get 请求,而是转入window.location
正确的 url。
所以转这个...
$.get("/api/acs_download", {acs_variable: acs_variable, state:state, acs_type:acs_type, year:year }, function(response){
console.log(response.exist);
});
进入这个:
var params = {acs_variable: acs_variable, state:state, acs_type:acs_type, year:year}
window.location.href = '/api/acs_download?' + $.param( params )
推荐阅读
- node.js - 如何将 DynamoDB Streams 对象映射到 Javascript 对象?
- r - 更改格子图例的字体
- java - Spring MVC:在同一网络服务器中的 WAR 之间共享 bean
- php - 登录问题。我正在使用 php 版本 7.2
- python - 如何将 tweepy api 调用转换为异步
- javascript - 在 ListView 中显示 Array 的每一项
- c# - 无法使用标准序列化时如何将 C# 对象传输到 C++
- react-redux - Redux-saga - yield all 不是在 root saga 中调用我所有的 saga
- sql - 在任何其他 SQL 之前先执行子查询重构
- regex - 正则表达式在整数之前提取字符串