0

I'am learning python and django, I want to make an endpoint that takes zip file and iterate through it and shows me the item list inside the zip file. What would be the easiest way to implement this? I have tried something, as my knowledge in django is not good at all.

from django.core.files.storage import FileSystemStorage
import zipfile

class Upload(View):
    def post(self, request):
        context = {}

        if request.method == 'POST':
            uploaded_file = request.FILES['filename']
            zf = zipfile.ZipFile(uploaded_file)
            print zf.namelist()


            for filename in zf.namelist():

                fs = FileSystemStorage()                    
                rename = 'uploadedFile.jpg'                 
                name = fs.save(rename, filename)            
                context['url'] = fs.url(name)               

        return render(request, 'app.html', context)

so basically my purpose is to take a zipfile from and rename it and makke an url for each. My stated code is not the right way to do this as its bringing some error, would you please help me with the right way?

Zeed Tanue
  • 91
  • 5
  • 24

1 Answers1

1

I haven't tested this code on live django project, but this is the way I'd code your task.

from zipfile import ZipFile

def get_filenames(path_to_zip):
    """ return list of filenames inside of the zip folder"""
    with ZipFile(path_to_zip, 'r') as zip:
        return zip.namelist()

and in your view:

class Upload(View):
    def post(self, request):
        # as you use class based views you can skip the check of request type (request.method == 'POST'). 
        # It always will be POST as it post() method
        filenames = get_filenames('your_zip.zip')           
        return render(request, 'app.html', {'filenames': filenames})

It's just example, but you can add some more extra logic, like renaming etc.

P.S. Can't add a comment, but if you are on python3 and got SyntaxError on

print zf.namelist()

just wrap it in brackets:

print(zf.namelist())
bigEvilBanana
  • 388
  • 2
  • 8