0

I want to delete the generated zipfile from the server, after the end user downloads it into the local system in Django Python web application.

My question is similar to this question asked already by another user

But, the solution suggested on that link shared above requires me to import a this line:

from webapp.celery import app

I am not sure how to install this library? Any idea on this how to make use of the suggested solution on the link Thank you.

Sri2110
  • 335
  • 2
  • 19
  • the answer used celery to remove the zip file,https://pypi.org/project/celery/, and the task_delete_zipfile method is called with delay, So it may happen later point of time. I believe for just remove old zip files including celery is an overhead, If your project has other things to do with clelery ( some time consuming tasks which may go beyond the http request timeout, cron type tasks ....) go for celery. Oher wise you can try 'temp file' which will be destroyed after use( after response sent). – Jisson May 16 '23 at 08:13
  • https://stackoverflow.com/questions/34249632/how-to-serve-a-created-tempfile-in-django https://itecnote.com/tecnote/python-how-to-serve-a-created-tempfile-in-django/ – Jisson May 16 '23 at 08:18

1 Answers1

1

maybe u can try like this:

import os
from django.http import HttpResponse
from django.views import View

class MyDownloadView(View):
    def get(self, request):
        # code etc..
        zipfile_path = "/path/to/generated/zipfile.zip"  # Replace with the actual path

        # Open the file for reading and serve it to the user
        with open(zipfile_path, 'rb') as file:
            response = HttpResponse(file.read(), content_type='application/zip')
            response['Content-Disposition'] = 'attachment; filename="downloaded.zip"'

        # Delete the zipfile from the server
        os.remove(zipfile_path)

        return response
Carmelot
  • 46
  • 2
  • Hey @Carmelot, it tried this already, but for some reason, its now working ! – Sri2110 May 16 '23 at 07:41
  • @Sri2110 nice !! sometimes code does wonders we dont get why :) – Carmelot May 16 '23 at 08:09
  • @Sri2110: did you remove the file *before* returning the result? – Willem Van Onsem May 16 '23 at 08:17
  • Hey just figured out the reason, the zipfile was probably in use by other part of program and that it why it was not getting deleted, after using file handling to close the file post usage, it worked like a charm.! Thanks everyone for taking out the time to look into it :) – Sri2110 May 16 '23 at 08:39