Flask-下载后删除上传 [英] Flask- Deleting uploads after they have been downloaded

查看:531
本文介绍了Flask-下载后删除上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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



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



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

/api/#flask.after_this_requestrel =nofollow noreferrer> after_this_request 装饰器可以用于这个用例:

  @ app.route('/ files /< filename> / download')
def download_file(filename):
file_path = derive_filepath_from_filename (文件名)
file_handle = open(file_path,'r')
@after_this_request $ b $ def remove_file(响应):
try:
os.remove(file_path)
file_handle.close()
除了异常作为错误:
app.logger.error(错误消除或关闭下载文件句柄,错误)
返回响应
返回send_file(file_handle)

问题在于这将会是

I am currently working on a small web interface which allows different users to upload files, convert the files they have uploaded, and download the converted files. The details of the conversion are not important for my question.

I am currently using flask-uploads to manage the uploaded files, and I am storing them in the file system. Once a user uploads and converts a file, there are all sorts of pretty buttons to delete the file, so that the uploads folder doesn't fill up.

I don't think this is ideal. What I really want is for the files to be deleted right after they are downloaded. I would settle for the files being deleted when the session ends.

I've spent some time trying to figure out how to do this, but I have yet to succeed. It doesn't seem like an uncommon problem, so I figure there must be some solution out there that I am missing. Does anyone have a solution?

解决方案

Flask has an after_this_request decorator which could work for this use case:

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

The issue is that this will only work well on Linux (which lets the file be read even after deletion if there is still an open file pointer to it).

这篇关于Flask-下载后删除上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆