如何清理与 send_file 一起使用的临时文件? [英] How to clean up temporary file used with send_file?

查看:22
本文介绍了如何清理与 send_file 一起使用的临时文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个服务器端 json 接口,其中有几个临时文件在请求期间被操作.

I'm currently developing a server side json interface where several temporary files are manipulating during requests.

我当前在请求结束时清理这些文件的解决方案如下所示:

My current solution for cleaning up these files at the end of the request looks like this:

@app.route("/method",methods=['POST'])
def api_entry():
    with ObjectThatCreatesTemporaryFiles() as object:
        object.createTemporaryFiles()
        return "blabalbal"

在这种情况下,清理需要在 object.__exit__() 中进行

In this case, the cleanup takes lace in object.__exit__()

但是在少数情况下,我需要向客户端返回一个临时文件,在这种情况下,代码如下所示:

However in a few cases I need to return a temporary files to the client, in which case the code looks like this:

@app.route("/method",methods=['POST'])
def api_entry():
    with ObjectThatCreatesTemporaryFiles() as object:
        object.createTemporaryFiles()
        return send_file(object.somePath)

这目前不起作用,因为当我进行清理时,flask 正在读取文件并将其发送给客户端.¨我该如何解决这个问题?

This currently does not work, because when I the cleanup takes place flask is in the process of reading the file and sending it to the client. ¨ How can I solve this?

我忘了提到文件位于临时目录中.

I Forgot to mention that the files are located in temporary directories.

推荐答案

我使用的方法是在响应完成后使用弱引用删除文件.

The method I've used is to use weak-references to delete the file once the response has been completed.

import shutil
import tempfile
import weakref

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)

file_remover = FileRemover()

在我的烧瓶电话中:

@app.route('/method')
def get_some_data_as_a_file():
    tempdir = tempfile.mkdtemp()
    filepath = make_the_data(dir_to_put_file_in=tempdir)
    resp = send_file(filepath)
    file_remover.cleanup_once_done(resp, tempdir)
    return resp

这是非常通用的方法,并且在我使用过的三个不同的 Python Web 框架中都有效.

This is quite general and as an approach has worked across three different python web frameworks that I've used.

这篇关于如何清理与 send_file 一起使用的临时文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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