首页 > 解决方案 > 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"})

标签: javascriptpythonhtmlflask

解决方案


您需要用户重定向到要下载文件的位置。因此,您无需发出 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 )

推荐阅读