【问题标题】:Delete an uploaded file after downloading it from Flask从 Flask 下载后删除上传的文件
【发布时间】:2014-08-28 00:57:54
【问题描述】:

我目前正在开发一个小型 Web 界面,该界面允许不同的用户上传文件、转换他们上传的文件以及下载转换后的文件。转换的细节对我的问题并不重要。

我目前正在使用flask-uploads 来管理上传的文件,并将它们存储在文件系统中。一旦用户上传并转换文件,就会有各种漂亮的按钮来删除文件,这样上传文件夹就不会被填满。

我认为这并不理想。我真正想要的是文件在下载后立即被删除。我会接受会话结束时删除的文件。

我花了一些时间试图弄清楚如何做到这一点,但我还没有成功。这似乎不是一个不常见的问题,所以我认为肯定有一些我缺少的解决方案。有人有解决办法吗?

【问题讨论】:

    标签: python flask


    【解决方案1】:

    有几种方法可以做到这一点。

    send_file 然后立即删除(仅限 Linux)

    Flask 有一个 after_this_request 装饰器,可以用于这个用例:

    @app.route('/files/<filename>/download')
    def download_file(filename):
        file_path = derive_filepath_from_filename(filename)
        file_handle = open(file_path, 'r')
        @after_this_request
        def remove_file(response):
            try:
                os.remove(file_path)
                file_handle.close()
            except Exception as error:
                app.logger.error("Error removing or closing downloaded file handle", error)
            return response
        return send_file(file_handle)
    

    问题是这将only work on Linux(如果仍然有一个打开的文件指针指向它,即使在删除之后也可以读取文件)。它也不会总是工作(我听说有时send_file 在文件已经被 Flask 取消链接之前不会结束内核调用)。它不会占用 Python 进程来发送文件。

    流文件,然后删除

    理想情况下,您应该在知道操作系统已将文件流式传输到客户端后清理文件。您可以通过创建一个流式传输文件然后关闭它的生成器,通过 Python 将文件流式传输回来,就像建议的 in this answer:

    def download_file(filename):
        file_path = derive_filepath_from_filename(filename)
        file_handle = open(file_path, 'r')
    
        # This *replaces* the `remove_file` + @after_this_request code above
        def stream_and_remove_file():
            yield from file_handle
            file_handle.close()
            os.remove(file_path)
    
        return current_app.response_class(
            stream_and_remove_file(),
            headers={'Content-Disposition': 'attachment', 'filename': filename}
        )
    

    这种方法很好,因为它是跨平台的。然而,它并不是灵丹妙药,因为它会绑定 Python Web 进程,直到整个文件都被流式传输到客户端。

    清理计时器

    在计时器上运行另一个进程(也许使用cron)或使用像APScheduler 这样的进程内调度程序并清理超出超时时间(例如半小时)在临时位置上的文件,一周,三十天,在 RDMBS 中标记为“已下载”之后)

    这是最稳健的方式,但需要额外的复杂性(cron、进程内调度程序、工作队列等)

    【讨论】:

    • ooo,不知道 after_this_request 处理程序
    • 另外一个问题:你知道在所有这些之后刷新页面的简单方法吗?
    • @after_this_request 如果我在 html 中播放视频,然后从 temp 中删除视频,则有效?有任何超时吗?
    • 不幸的是,在处理程序中调用file_handle.close() 会导致ValueError: read of closed file 或ValueError: I/O operation on closed file.。不过,无需关闭即可工作。
    【解决方案2】:

    您还可以将文件存储在内存中,删除它,然后提供您在内存中的内容。

    例如,如果您提供的是 PDF:

    import io
    import os
    
    @app.route('/download')
    def download_file():
        file_path = get_path_to_your_file()
    
        return_data = io.BytesIO()
        with open(file_path, 'rb') as fo:
            return_data.write(fo.read())
        # (after writing, cursor will be at last byte, so move it to start)
        return_data.seek(0)
    
        os.remove(file_path)
    
        return send_file(return_data, mimetype='application/pdf',
                         attachment_filename='download_filename.pdf')
    

    (以上我只是假设它是 PDF,但如果需要,您可以通过编程方式 get the mimetype)

    【讨论】:

    • 非常感谢。抱歉迟到了评论,但这种技术在生产阶段有缺点吗?
    • @KeremNayman 据我所知,没有生产劣势。我们在我所在的初创公司的生产中使用了这个技巧。
    • 优秀的解决方案!这是我见过的唯一一个不依赖线程技巧、计时器等的解决方案。非常可靠!谢谢!
    • 谢谢,加勒特!
    【解决方案3】:

    根据@Garrett 评论,更好的方法是在删除文件时不要阻止send_file。恕我直言,更好的方法是在后台将其删除,如下所示更好:

    import io
    import os
    from flask import send_file
    from multiprocessing import Process
    
    @app.route('/download')
    def download_file():
        file_path = get_path_to_your_file()
    
        return_data = io.BytesIO()
        with open(file_path, 'rb') as fo:
            return_data.write(fo.read())
            return_data.seek(0)    
    
        background_remove(file_path)
    
        return send_file(return_data, mimetype='application/pdf',
                         attachment_filename='download_filename.pdf')
    
    
    def background_remove(path):
        task = Process(target=rm(path))
        task.start()
    
        
    def rm(path):
        os.remove(path)
    

    【讨论】:

    • 为什么最好为此生成一个进程?这不会更慢吗?在我的机器上测试,background_remove(file_path) 行阻塞 3,063 µs,而 os.remove(path) 阻塞 65 µs。
    • 很好,这取决于文件大小,此外,您要删除的文件数量。
    【解决方案4】:

    Flask 有一个 after_request 装饰器,可以在这种情况下工作:

    @app.route('/', methods=['POST'])
        def upload_file():
        uploaded_file = request.files['file']
        file = secure_filename(uploaded_file.filename)
    
        @app.after_request
        def delete(response):
            os.remove(file_path)
            return response
    
        return send_file(file_path, as_attachment=True, environ=request.environ)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-06
      • 1970-01-01
      • 2017-04-12
      相关资源
      最近更新 更多