在Windows Server上使用flask python的send_file()返回后删除临时文件夹

问题描述 投票:0回答:1

我正在尝试删除一个临时文件夹,在其中保存图像并对其进行一些处理,然后返回一些结果。我使用了shutil.rmtree(filepath),它在Mac OS上可以正常工作。但是,当我在Windows服务器上运行它时,它失败并显示一条错误,指出文件仍在使用中。

我在堆栈溢出How to clean up temporary file used with send_file?时提到了这个问题>

This answer使用弱引用有助于消除Windows上引发的错误,但仍不会删除该文件夹。尽管在Mac OS上仍然可以正常使用。

在Windows系统上完成请求后,如何删除临时文件夹?

这是我的代码段供您参考。

    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 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)

我正在尝试删除一个临时文件夹,在其中保存图像并对其进行一些处理,然后返回一些结果。我使用了shutil.rmtree(filepath),它在Mac OS上可以正常工作。但是当...

python flask flask-restful
1个回答
0
投票

您正在使用ignore_errors=True,它将隐藏shutil.rmtree遇到的任何异常。

© www.soinside.com 2019 - 2024. All rights reserved.