有几种方法可以做到这一点。
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、进程内调度程序、工作队列等)