Search code examples
flaskpython-3.5temporary-filessendfile

Flask send temporary file using send_file


I am trying to send an xlsx file to a user. I have it writing to a temporary file, but I'm getting the following error:

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

I'm not sure how to correct this... below is my code to create the temp file. Any guidance or suggestions are welcome and appreciated:

    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')

Solution

  • TempFile disappears at tmp.close() I updated to use tmp.mkstemp()

    That corrected my issue