0
votes

i create a function that create a thumbnail when uploading an image. I can upload the image and create the thumbnail out of it. But the result that i got is the thumbnail was created more than one until and i got the error that i've mention aboved.

def save(self, *args, **kwargs):
        """
        Make and save the thumbnail for the photo here.
        """
        super(AerialFoto, self).save(*args, **kwargs)
        if not self.make_thumbnail():
            raise Exception('Could not create thumbnail - is the file type valid?')

    def make_thumbnail(self):
        """
        Create and save the thumbnail for the photo (simple resize with PIL).
        """
        THUMB_SIZE = (100,100)
        fh = storage.open(self.image.name, 'rb')
        try:
            image = Image.open(fh)
        except:
            return False

        image.thumbnail(THUMB_SIZE, Image.ANTIALIAS)
        fh.close()

        # Path to save to, name, and extension
        thumb_name, thumb_extension = os.path.splitext(self.image.name)
        thumb_extension = thumb_extension.lower()

        thumb_filename = thumb_name + 'thumbs' + thumb_extension

        if thumb_extension in ['.jpg', '.jpeg']:
            FTYPE = 'JPEG'
        elif thumb_extension == '.gif':
            FTYPE = 'GIF'
        elif thumb_extension == '.png':
            FTYPE = 'PNG'
        else:
            return False    # Unrecognized file type

        # Save thumbnail to in-memory file as StringIO
        temp_thumb = StringIO()
        image.save(temp_thumb, FTYPE)
        temp_thumb.seek(0)

        # Load a ContentFile into the thumbnail field so it gets saved
        self.thumbnail.save(thumb_filename, ContentFile(temp_thumb.read()), save=True)
        temp_thumb.close()

Traceback http://dpaste.com/1ZG838R

2
In save() you call make_thumbnail() and in make_thumbnail() you are calling save(). This create a recursion without end. - Klaus D.

2 Answers

0
votes

save() calls make_thumbnail(), which calls self.thumbnail.save(...), which ends up calling save() again, and around and around it goes.

You have to break the loop somewhere. My suggestion: make_thumbnail() shouldn't save anything, it should just create the thumbnail and store it on say self._thumbnail_data= temp_thumb.read();.

Then in the save() function, only call self.make_thumbnail() if self._thumbnail_data isn't already set. Once you know self._thumbnail_data exists then you can do self.thumbnail.save(thumb_filename, self._thumbnail_data, save=True).

0
votes

This happens because save calls make_thumbnail and make_thumbnail calls save and when number of calls exeeds sys.getrecursionlimit() RuntimeError - maximum recursion depth exceeded Error is raised.