Problem trying to remove a file after download in Flask

116 Views Asked by At

I am writing a small web application in flask that allows users to upload audio files, process them, and then download the processed files. The problem I'm having is that after the file is processed and downloaded, I can't remove it from the server. I have tried the after_this_request decorator, but all I get is an error message saying that the file is in use. I'm running the app using localhost.

This is my actual code:

@app.route("/download")
def download():
    # get the file path parameter from the URL
    file_path = request.args.get('file_path')

    response = send_file(file_path, as_attachment=True)

    # use Flask's send_file function to send the file to the user for download
    @after_this_request
    def delete_file(response):
        try:
            if os.path.isfile(file_path):
                os.remove(file_path)
            else:
                print(f"Error: {file_path} not found")
        except Exception as e:
            print(f"Error deleting {file_path}: {e}")
        return response

    return response

the app is fully working as intended but I'm struggling to solve this last problem and still can't find a solution...

I tried everything, I tried using the after_this_request decorator, the os.remove(file_path) alone. I know the problem is there because without using send_file() action and trying to remove the file via os.remove works as intended.

0

There are 0 best solutions below