lte__
lte__

Reputation: 7586

Delete file after returning?

I have a locally saved Excel file on my Flask server that I generated from a Pandas df df_output and I want to send and then delete.

I'm kinda doing

@app.route('/getfile', methods=['GET', 'OPTIONS'])
@crossdomain(origin='*')
def get_file():
    #Generate an Excel file from he df_outfut Pandas dataframe, save it to disk:
    out_filename = "testfile"
    writer = pd.ExcelWriter(out_filename)
    df_output.to_excel(writer,'test', index=False)
    writer.save()
    return send_file(os.path.join(app.config['UPLOAD_FOLDER'], filename), as_attachment=True)

This way I can do window.open("http://myapi/getfile") and the file downloads to my local computer. However, I would not like to store the file on the server after it's been downloaded. BUT I send it with a return statement, so I cannot delete it afterwards. What would be a way to delete the generated file after sending it? Basically I'm looking to:

return send_file(os.path.join(app.config['UPLOAD_FOLDER'], filename), as_attachment=True)
os.remove(filename)

which obviously won't work.

Upvotes: 3

Views: 1929

Answers (1)

Joost
Joost

Reputation: 3729

The trick is to not save your file on the hard drive at all, but storing it in memory instead:

from flask import Flask, send_from_directory, make_response
import pandas as pd
from io import BytesIO

app = Flask(__name__)

@app.route('/getfile', methods=['GET', 'OPTIONS'])
def get_file():
    datadump = BytesIO()
    df = pd.DataFrame(data={'col1': [1, 2], 'col2': [3, 4]})
    writer = pd.ExcelWriter(datadump)
    df.to_excel(writer, 'test', index=False)
    writer.save()
    response = make_response(datadump.getvalue())
    response.mimetype = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    response.headers.set('Content-Disposition', 'attachment', filename='test.xlsx')
    return response

Upvotes: 1

Related Questions