簡體   English   中英

Flask-獲取數據框以csv格式下載

[英]Flask - Get a dataframe to download as 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 )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM