0

I am trying to delete a temporary folder where I save an image and do some processing on it and then return some results. I used shutil.rmtree(filepath) and it works correctly on Mac OS. However when I run it on Windows server, it fails with an error saying file is still in use.

I referred this question on stack overflow How to clean up temporary file used with send_file?

This answer using weak references helps in removing the error that was thrown on Windows, but the folder is still not deleted. Though it still works correctly on Mac OS.

How can I delete the temporary folder after the request has been completed on Windows system?

Here is my code snippet for your reference.

    def post(self):
    try:
        if 'photo' not in request.files:
            raise NoFilesError
        file = request.files['photo']
        print('file = ', file)
        if file.filename == '':
            raise NoFilesError
        if file and self._allowed_file(file.filename):
            filename = secure_filename(file.filename)
            dir_path = os.path.join(BaseAPIConfig.UPLOAD_FOLDER, get_timestamp())
            create_directory(dir_path)
            file_path = os.path.join(dir_path, filename)
            file.save(file_path)
            img_proc_main(dir_path, filename)
            image_filename = filename.rsplit('.', 1)[0]
            image_format = filename.rsplit('.', 1)[1]
            result_file = os.path.join(dir_path, image_filename + '_bb.' + image_format)
            response = make_response(send_file(result_file))
            file_remover = FileRemover()
            file_remover.cleanup_once_done(response, dir_path)
            return response
            ...

FileRemover class

class FileRemover(object):
    def __init__(self):
        self.weak_references = dict()  # weak_ref -> filepath to remove

    def cleanup_once_done(self, response, filepath):
        wr = weakref.ref(response, self._do_cleanup)
        self.weak_references[wr] = filepath

    def _do_cleanup(self, wr):
        filepath = self.weak_references[wr]
        print('Deleting %s' % filepath)
        shutil.rmtree(filepath, ignore_errors=True)
edeesan
  • 326
  • 3
  • 16

1 Answers1

0

You are using ignore_errors=True, which hides away any exception that shutil.rmtree encounters.

There are many reasons why shutil.rmtree might fail to remove the directory—perhaps you simply don't have the correct permission on Windows. Setting ignore_errors to false will give you more indications of what's going on.

xcmkz
  • 677
  • 4
  • 15
  • Exception ignored in: > PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'D:\\bb_upload_folder\\1589722538\\R_15_1_bb.jpeg' This is the exception thrown when set ignore_errors=False – edeesan May 17 '20 at 16:33
  • In that case you need to close the file or kill the process that has it open first – xcmkz May 17 '20 at 16:43