【问题标题】:Download CSV file to the client将 CSV 文件下载到客户端
【发布时间】:2019-11-16 01:34:04
【问题描述】:

我有以下路线:

@app.route('/download/', methods=['GET'])
def download():
    output_filename = request.args.get('output_filename')
    data = dict(foos=[1,2,3,3,2,1], bars=[7,7,7,7,7,7])
    df = pd.DataFrame(data)
    result = df.to_csv(index=False)
    response = make_response(result)
    response.headers['Content-Disposition'] = f'attachment; filename={output_filename}'
    response.headers['Cache-Control'] = 'must-revalidate'
    response.headers['Pragma'] = 'must-revalidate'
    response.headers['Content-type'] = 'application/csv'
    return response

我用 AJAX 调用如下:

function download(data, handler = null) {
  let data = {output_filename: "foo.csv"};
  let url = "/download/";
  $.ajax({
    type: "GET",
    url: url,
    data: data,
    success: function(data) {
      console.log('success');
    },
  });
}

但是,客户端没有显示任何内容。我在这里遗漏了什么吗?

【问题讨论】:

  • if def download(): is just a return with data 你得到什么吗?
  • 是的——我觉得我在这里有点菜鸟。 success: ... 返回 CSV 数据,所以想 stackoverflow.com/q/4545311/5058116 可能有答案...
  • 我赞成你的问题,因为我认为这是一个很棒的问题。许多文档似乎忘记了在函数完成之前您可能实际上需要取回数据的情况。
  • @oppressionslayer 我将success闭包中的数据作为CSV字符串获取,但我想知道为什么它没有将其写入文件
  • 如果您希望浏览器解释内容处置标头等,请使其成为对服务器的直接获取请求,而不是 ajax。创建带有下载 url 的 html 元素并在其上触发点击事件。

标签: python csv flask download


【解决方案1】:

我比 ajax 更熟悉 node(我在 nodejs 中遇到了同样的问题,我在 stackoverflow 上修复了这个问题),但也许这会有所帮助:

$.ajax({
    async: false,

来自How do I make jQuery wait for an Ajax call to finish before it returns?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-19
    • 1970-01-01
    • 2011-04-02
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多