Esempio n. 1
0
def process_zipfile(uploaded_album):
    if default_storage.exists(uploaded_album.zip_file.name):
        # TODO: implement try-except here
        zip = zipfile.ZipFile(uploaded_album.zip_file)
        bad_file = zip.testzip()
        if bad_file:
            raise Exception('"%s" in the .zip archive is corrupt.' % bad_file)

        if not uploaded_album.album:
            try:
                uploaded_album.album = Album.objects.get(name=uploaded_album.new_album_name,
                                                         user=uploaded_album.user)
            except Album.DoesNotExist:
                uploaded_album.album = Album.objects.create(name=uploaded_album.new_album_name,
                                                            user=uploaded_album.user)

        from cStringIO import StringIO
        for filename in sorted(zip.namelist()):
            if filename.startswith('__'):  # do not process meta files
                continue
            # print filename.encode('ascii', errors='replace')
            data = zip.read(filename)
            if len(data):
                try:
                    # the following is taken from django.forms.fields.ImageField:
                    # load() could spot a truncated JPEG, but it loads the entire
                    # image in memory, which is a DoS vector. See #3848 and #18520.
                    # verify() must be called immediately after the constructor.
                    PILImage.open(StringIO(data)).verify()
                except Exception, ex:
                    # if a "bad" file is found we just skip it.
                    print('Error verify image: %s' % ex.message)
                    continue
                if hasattr(data, 'seek') and callable(data.seek):
                    print 'seeked'
                    data.seek(0)
                try:
                    img = Image()
                    img.image.save(filename, ContentFile(data))
                    img.user = uploaded_album.album.user
                    img.title = reverse_slug(filename, remove_extension=True, title=True)
                    img.tags = uploaded_album.tags
                    img.save()

                    AlbumImage.objects.create(album=uploaded_album.album,
                                              image=img,
                                              order=0)
                except Exception, ex:
                    print('error create Image: %s' % ex.message)