Flask-删除上传后的上传内容

sea*_*ook 13 python flask

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

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

我不认为这是理想的.我真正想要的是在下载文件后立即删除它们.我会满足于会话结束时被删除的文件.

我花了一些时间试图弄清楚如何做到这一点,但我还没有成功.这似乎不是一个不寻常的问题,所以我认为必须有一些解决方案,我错过了.有没有人有办法解决吗?

Sea*_*ira 26

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

@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)
Run Code Online (Sandbox Code Playgroud)

问题是这只能在Linux上运行良好(如果仍有一个打开的文件指针,它甚至可以在删除后读取文件).


Gar*_*ett 13

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

例如,如果您正在提供 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')
Run Code Online (Sandbox Code Playgroud)

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