Esempio n. 1
0
 def process_zipfile(self):
     if os.path.isfile(self.zip_file.path):
         # TODO: implement try-except here
         zip = zipfile.ZipFile(self.zip_file.path)
         bad_file = zip.testzip()
         if bad_file:
             raise Exception('"%s" in the .zip archive is corrupt.' % bad_file)
         count = 1
         album = self.album
         if not album:
             album = Album.objects.create(name=self.new_album_name)
         from cStringIO import StringIO
         for filename in sorted(zip.namelist()):
             if filename.startswith('__'): # do not process meta files
                 continue
             data = zip.read(filename)
             if len(data):
                 try:
                     # the following is taken from django.newforms.fields.ImageField:
                     #  load() is the only method that can spot a truncated JPEG,
                     #  but it cannot be called sanely after verify()
                     trial_image = PILImage.open(StringIO(data))
                     trial_image.load()
                     # verify() is the only method that can spot a corrupt PNG,
                     #  but it must be called immediately after the constructor
                     trial_image = PILImage.open(StringIO(data))
                     trial_image.verify()
                 except Exception:
                     # if a "bad" file is found we just skip it.
                     continue
                 img = Image(album=album)
                 img.image.save(filename, ContentFile(data))
                 img.save()
         zip.close()
         return album