Flask使用send_file发送临时文件

时间:2017-04-26 17:06:25

标签: flask python-3.5 temporary-files sendfile

我正在尝试将xlsx文件发送给用户。我把它写入临时文件,但是我收到以下错误:

TypeError: invalid file: <tempfile._TemporaryFileWrapper object at 0x04A79F90>

我不确定如何纠正这个...下面是我创建临时文件的代码。欢迎并赞赏任何指导或建议:

    price_tf = tempfile.TemporaryFile()
    writer = pd.ExcelWriter(price_tf, engine='xlsxwriter')
    price_list_df.to_excel(writer, sheet_name='Price List')
    workbook = writer.book
    worksheet = writer.sheets['Price List']
    writer.sheets['Price List'].set_column('C:C', 45)
    writer.sheets['Price List'].set_column('D:D', 65)
    writer.sheets['Price List'].set_column('E:E', 12)
    writer.sheets['Price List'].set_column('F:F', 6)
    writer.save()
    writer.close()
    myio = io.StringIO()
    with open(price_tf, 'rb') as f:
        data = f.read()

    myio.write(data)
    myio.seek(0)
    send_file(myio, attachment_filename="price_list.xlsx", as_attachment=True, mimetype='text/xlsx')

1 个答案:

答案 0 :(得分:0)

TempFile在tmp.close()消失 我更新为使用tmp.mkstemp()

纠正了我的问题