在django中返回HttpResponse后删除tmp文件 [英] Removing tmp file after return HttpResponse in django

查看:1156
本文介绍了在django中返回HttpResponse后删除tmp文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下django / python代码将文件流式传输到浏览器:

I'm using the following django/python code to stream a file to the browser:

wrapper = FileWrapper(file(path))
response = HttpResponse(wrapper, content_type='text/plain')
response['Content-Length'] = os.path.getsize(path)
return response

在返回响应后有没有办法删除文件?使用回调函数还是什么?
我可以做一个cron来删除所有的tmp文件,但是如果我可以从同一个请求中流式传输文件并删除它们,那将会更加简单。

Is there a way to delete the file after the reponse is returned? Using a callback function or something? I could just make a cron to delete all tmp files, but it would be neater if I could stream files and delete them as well from the same request.

推荐答案

您可以使用NamedTemporaryFile:

You can use a NamedTemporaryFile:

from django.core.files.temp import NamedTemporaryFile
def send_file(request):
    newfile = NamedTemporaryFile(suffix='.txt')
    # save your data to newfile.name
    wrapper = FileWrapper(newfile)
    response = HttpResponse(wrapper, content_type=mime_type)
    response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(modelfile.name)
    response['Content-Length'] = os.path.getsize(modelfile.name)
    return response

一旦新文件对象被驱逐,临时文件应该被删除。

temporary file should be deleted once the newfile object is evicted.

这篇关于在django中返回HttpResponse后删除tmp文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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