Py学习  »  Python

python flask-如果文件扩展名为xls,则不返回输出

dark horse • 4 年前 • 303 次点击  

我有一个小烧瓶项目,它从用户那里获取一些输入,并根据输入从数据库中提取一些数据返回给用户,然后返回一个输出文件。

如果文件格式是csv,代码就可以正常工作。但是,当文件格式为xls时,我看到正在生成输出,但是flask应用程序不返回文件。

编辑:

下面给出了 视图.py

@app.route('/data', methods=['GET','POST'])
def data():
    form = DataForm()
    if form.validate_on_submit():
        name = form.name.data
        start_date = form.start_date_field.data
        end_date = form.end_date_field.data
        file_extension = form.file_extension_field.data

        rep_func(name=name, start_date=start_date, end_date=end_date, exten=file_extension)

        current_directory = path.abspath(path.join(__file__, ".."))
        base = os.path.join(current_directory, 'files')

        if file_extension == 'csv':
            data = pd.read_csv(base + f'/final_output/{name}_{end_date}.{file_extension}', sep=r',(?!\s|\Z)', engine='python') 
            resp = make_response(data.to_csv(index=False))
            resp.headers["Content-Disposition"] = f'attachment; filename={name}_{end_date}.{file_extension}'
            resp.headers["Content-Type"] = "text/csv"
        elif file_extension == 'xls':
            data = pd.read_excel(base + f'/final_output/{name}_{end_date}.{file_extension}')
            resp = make_response(data.to_excel(index=False))
            resp.headers["Content-Disposition"] = f'attachment; filename={name}_{end_date}.{file_extension}'
            resp.headers["Content-Type"] = "application/vnd.ms-excel"
            return resp

    return render_template('file.html', form=form)

有人能告诉我这件事哪里不对吗?谢谢

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/46978
 
303 次点击