Flask send_file作为附件无响应

时间:2018-06-27 10:26:16

标签: javascript python jquery flask

我用烧瓶编写了一个jQuery,在单击时应执行SQL搜索并将数据框导出为ex​​cel,脚本为:

<script type=text/javascript>
$(function () {
    $('a#export_to_excel').bind('click', function () {
        $.getJSON($SCRIPT_ROOT + ' /api/sanctionsSearch/download', {
            nm: $('input[name="nm"]').val(),
            searchtype: $('select[name="searchtype"]').val()
        }, function (data) {
            $("#download_results").text(data.result);
        });
        return false;
    });
});

但是浏览器没有响应,我的python代码如下:

from io import BytesIO,StringIO
from flask import render_template, request, url_for, jsonify, redirect, request, Flask, send_file

def index():

#get the dataframe ready and define as 'data', parameters obtained from form input in html

name = request.args.get('nm','', type = str)
type = request.args.get('searchtype','Entity',type = str)

#function get_entity() to get the dataframe
#I have checked and the dataframe is functioning properly
data = get_entity(name,type)

#check if the dataframe is empty
if data.empty == True:
    print("its not working bruh...")
    word = "No results to export! Please try again!"
    return jsonify(result = word)

#store the csv to BytesIO 
proxy = StringIO()
data.to_csv(proxy)
mem = BytesIO()
mem.write(proxy.getvalue().encode('utf-8'))

mem.seek(0)
proxy.close()

print("download starting....")

#send file
send_file(mem, as_attachment=True,attachment_filename='Exportresults.csv', mimetype='text/csv')
word = "Download starting!"
return jsonify(result = word)

有人可以告诉我我的代码有什么问题吗?正确地将“下载开始...”打印到了html,但是下载根本没有开始。

2 个答案:

答案 0 :(得分:0)

该解决方案并不理想,但是我所做的是在jquery中添加了window.open(url)命令,该命令将调用另一个函数,该函数会将send_file发送给用户。

答案 1 :(得分:0)

您应该使用return语句

return send_file()