RuntimeError - 超出最大递归深度

时间:2015-11-15 13:34:03

标签: python django

我创建了一个在上传图像时创建缩略图的功能。我可以上传图像并从中创建缩略图。但我得到的结果是缩略图创建不止一个,直到我得到了我上面提到的错误。

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()

回溯 http://dpaste.com/1ZG838R

2 个答案:

答案 0 :(得分:0)

save()调用make_thumbnail(),调用self.thumbnail.save(...),最终再次调用save(),并在其周围转移。

你必须在某个地方打破循环。我的建议:make_thumbnail()不应保存任何内容,只需创建缩略图并将其存储在self._thumbnail_data= temp_thumb.read();上即可。

然后在save()函数中,如果self.make_thumbnail()尚未设置,则只调用self._thumbnail_data。知道self._thumbnail_data后,您就可以执行self.thumbnail.save(thumb_filename, self._thumbnail_data, save=True)

答案 1 :(得分:0)

这是因为save调用make_thumbnailmake_thumbnail调用save,并且调用次数sys.getrecursionlimit() 运行时错误 - 超出最大递归深度< / strong>引发错误。