0

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.

  • Please, in you code snippet, could you add your import statements as well? Because I think it could be related to missing the import of the `os` module. Since the `os.remove` is called within a try/catch its import can failed silently. – Martin Tovmassian Apr 10 '23 at 13:20
  • Sure! Here are my import statements: ```import os from flask import Flask, render_template, request, send_file, after_this_request, redirect, url_for from werkzeug.utils import secure_filename from dsp import compress from converter import mp3_converter from time import sleep import datetime import numpy as np import librosa import librosa.display import matplotlib.pyplot as plt import matplotlib matplotlib.use('Agg')``` – gmferronato Apr 10 '23 at 13:35
  • Ok strange...on my Linux environment it is working. I mean with your `os` and `flask` imports and your `download` method, the file is removed once your called the endpoint. – Martin Tovmassian Apr 10 '23 at 16:46

0 Answers0