1

I'm now making website that downloads certain images from other website, zip files, and let users download the zip file.

Everything works great, but I have no way to delete zip file from server, which has to be deleted after users download it.

I tried deleting temp directory that contains zip file with shutil.rmtree, but I couldn't find way to run it after HTTPResponse.

Here is my code in views.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

Thanks in advance.

wowkin2
  • 5,895
  • 5
  • 23
  • 66
devingryu
  • 35
  • 6

1 Answers1

0

You should looks to Celery project. It allows to schedule delayed function calls (after response generated).
So you can read that file to a variable and schedule task to remove that file.

# 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")

wowkin2
  • 5,895
  • 5
  • 23
  • 66