1

I'm working in a flask app that takes several files from a folder in the web server and creates a zip file that contains them to finally send that zip file to the user. My problem is that I do not manage to delete the zip file from the web server after sending it.

I've tried to solve the problem using the @after_this_request command.

Here I show a simplified version of the code I've written. I send the previously created zip file and then I try to delete it.

@app.route('/sendFile')
def sendFile():
    @after_this_request
    def removeFile(response):
        os.remove(zip_path)
        return response

    return send_from_directory(path, filename=zipname, as_attachment=True)

The problem is that an error is raised saying that the zip file cannot be deleted because it is still being used by other process. I've seen similar problems with other types of files:

Flask - delete file after download

Remove file after Flask serves it

However, they have not worked in my case with zip files.

SGH
  • 43
  • 1
  • 5

1 Answers1

7

You could read the file as bytes, delete the zip, then stream the response using flask.Response. Something like this might work:

from flask import Response

@app.route('/sendFile')
def sendFile():
    with open(os.path.join(path, zipname), 'rb') as f:
        data = f.readlines()
    os.remove(os.path.join(path, zipname))
    return Response(data, headers={
        'Content-Type': 'application/zip',
        'Content-Disposition': 'attachment; filename=%s;' % zipname
    })
tjholub
  • 678
  • 4
  • 7