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)