Delete the file after submitting it

I have a Flask view that generates data and saves it as a CSV file with Pandas and then displays the data. The second view serves the generated file. I want to delete the file after downloading it. My current code is causing a permission error, possibly because it after_requestdeletes the file before it is sent using send_from_directory. How can I delete a file after serving it?

def process_data(data)
    tempname = str(uuid4()) + '.csv'
    data['text'].to_csv('samo/static/temp/{}'.format(tempname))
    return file

@projects.route('/getcsv/<file>')
def getcsv(file):
    @after_this_request
    def cleanup(response):
        os.remove('samo/static/temp/' + file)
        return response

    return send_from_directory(directory=cwd + '/samo/static/temp/', filename=file, as_attachment=True)
+4
source share
1 answer

after_request , . ; , , .

, . , , , .

@app.route('/download_and_remove/<filename>')
def download_and_remove(filename):
    path = os.path.join(current_app.instance_path, filename)

    def generate():
        with open(path) as f:
            yield from f

        os.remove(path)

    r = current_app.response_class(generate(), mimetype='text/csv')
    r.headers.set('Content-Disposition', 'attachment', filename='data.csv')
    return r
+3

Source: https://habr.com/ru/post/1662192/


All Articles