Djang中HTTP响应后的文件销毁

2024-04-26 12:36:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在做的网站,从其他网站下载某些图像,压缩文件,并让用户下载压缩文件。你知道吗

一切都很好,但我没有办法从服务器上删除zip文件,必须在用户下载后删除。你知道吗

我尝试删除包含zip文件的temp目录shutil.rmtree公司,但在HTTPResponse之后我找不到运行它的方法。你知道吗

这是我的密码视图.py. 你知道吗

    zipdir = condown(idx)#condown creates zip file in zipdir
    logging.info(os.path.basename(zipdir))
    if os.path.exists(zipdir):
        with open(zipdir, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type="multipart/form-data")
            response['Content-Disposition'] = 'inline; filename=download.zip'
            return response
    raise Http404

提前谢谢。你知道吗


Tags: 文件path用户图像服务器os网站response
1条回答
网友
1楼 · 发布于 2024-04-26 12:36:18

你应该看看Celery project。它允许安排延迟函数调用(在生成响应之后)。
因此,您可以将该文件读取到一个变量并计划任务以删除该文件。你知道吗

# views.py
def some_view(request):
    zipdir = condown(idx)#condown creates zip file in zipdir
    logging.info(os.path.basename(zipdir))
    response = HttpResponseNotFound()
    if os.path.exists(zipdir):
        with open(zipdir, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type="multipart/form-data")
            response['Content-Disposition'] = 'inline; filename=download.zip'

    task_delete_zipfile.delay(zipdir)
    return response


# tasks.py
import os
from webapp.celery import app

@app.task
def task_delete_zipfile(filePath):
    if os.path.exists(filePath):
        os.remove(filePath)
    else:
        print("Can not delete the file as it doesn't exists")

相关问题 更多 >