首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python PIL在Django TemporaryUploadedFile上失败

Python PIL在Django TemporaryUploadedFile上失败
EN

Stack Overflow用户
提问于 2018-07-27 03:22:46
回答 1查看 212关注 0票数 0

我有一个成像工具,允许摄影师上传文件。上传后,我想检查上传的图像是否确实是有效的JPEG文件。

因此,我编写了以下验证函数:

代码语言:javascript
复制
    def validate_JPG(self, image):
    ''' JPEG validation check. '''
    # Since PIL offers a more rubust check to validate if the image
    # is an JPEG this is used instead of checking the file header.
    try:
        img = Image.open(image)
        if img.format != 'JPEG':
            raise JPEGValidationFailed()
        else:
            return True
    except IOError, e:
        self.logger.debug('Error in the JPG validation: {}'.format(e))
        return False

该函数从获取图像的upload视图中调用:

代码语言:javascript
复制
    uploaded_file = self.request.FILES.get('image_file')

    image_checksum = sha256(uploaded_file.read()).hexdigest()

    if Photos.objects.filter(image_checksum=image_checksum).exists():
        return Response({
            'uploadError': 'Image already exists.'
            }, status=status.HTTP_409_CONFLICT,)
    try:
        self.logger.debug('Parsing: IPTC and EXIF')
        exif, iptc = self.data_parser.process_file(uploaded_file)
    except JPEGValidationFailed, e:
        raise serializers.ValidationError({
            'uploadError': str(e)
            })

    except Exception, e:
        self.logger.error('Error in parsing the IPTC and EXIF data: {}'.format(e))
        raise serializers.ValidationError({
            'uploadError': 'Something has gone wrong.'
            })

这段代码一直运行得很好,但不知何故,它现在失败了。使用的是Pillow库,Pillow==3.0.0但更新到最新版本也不起作用。

遇到以下错误:

cannot identify image file <TemporaryUploadedFile: YV180707_7856.jpg (image/jpeg)>

此外,执行image.seek(0)也不起作用。

有人能帮我吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-27 04:44:28

好吧..。因此,在休息一下并再次检查代码后,我注意到在将上传的文件传递给视图之前,有一个文件写入了该文件(backup-save):

代码语言:javascript
复制
  file.write(image_file.read())

所以这个文件已经读过一次了。在将其传递给视图之前,我必须放置一个image_file.seek(0) ……这就是解决之道。希望它最终能帮助到某个人。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51546166

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档