Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python ImageField未验证_Python_Django - Fatal编程技术网

Python ImageField未验证

Python ImageField未验证,python,django,Python,Django,为什么Django的ImageField没有在这里抛出验证错误 #模型中的字段 image\u mobile=ImageField( 将_上传到class='static/images/', 空白=真, 空=真 ) #试验中 从django.core.files.uploadedfile导入SimpleUploadedFile 附件=SimpleUploadedFile(“file.mp4”,b“file\u content”,content\u type=“text/plain”) obj.i

为什么Django的
ImageField
没有在这里抛出验证错误

#模型中的字段
image\u mobile=ImageField(
将_上传到class='static/images/',
空白=真,
空=真
)
#试验中
从django.core.files.uploadedfile导入SimpleUploadedFile
附件=SimpleUploadedFile(“file.mp4”,b“file\u content”,content\u type=“text/plain”)
obj.image_mobile=附件
obj.save()
self.assertEqual(obj.image\u mobile,“”)
输出如下:

AssertionError: <ImageFieldFile: static/images/file_7wanB5P.mp4> != ''
AssertionError:!=''
从文件中:

从FileField继承所有属性和方法,但也验证上载的对象是否为有效图像


看来这取决于PIL图书馆。Django使用它来获取图像尺寸,它似乎是ImageField的唯一验证。 它获取文件的前1024个字节并读取元数据,mp4和jpeg可能有类似的数据。因此,这不是最可靠的检查方法

 try:
    # Most of the time Pillow only needs a small chunk to parse the image
    # and get the dimensions, but with some TIFF files Pillow needs to
    # parse the whole file.
    chunk_size = 1024
    while 1:
        data = file.read(chunk_size)
        if not data:
            break
        try:
            p.feed(data)
        except zlib.error as e:
            # ignore zlib complaining on truncated stream, just feed more
            # data to parser (ticket #19457).
            if e.args[0].startswith("Error -5"):
                pass
            else:
                raise
        except struct.error:
            # Ignore PIL failing on a too short buffer when reads return
            # less bytes than expected. Skip and feed more data to the
            # parser (ticket #24544).
            pass
        except RuntimeError:
            # e.g. "RuntimeError: could not create decoder object" for
            # WebP files. A different chunk_size may work.
            pass
        if p.image:
            return p.image.size
        chunk_size *= 2
    return (None, None)
finally:
    if close:
        file.close()
    else:
        file.seek(file_pos)
def to_python(self,data):
"""
检查文件上载字段数据是否包含有效的图像(GIF、JPG、,
PNG等——任何枕头支撑)。
"""
f=super()。到python(数据)
如果f为无:
一无所获
从PIL导入图像
#我们需要一个枕头的文件对象。我们可能有一条路,或者
#必须将数据读入内存。
如果hasattr(数据“临时文件路径”):
文件=数据。临时文件路径()
其他:
如果hasattr(数据“读取”):
file=BytesIO(data.read())
其他:
file=BytesIO(数据['content'])
尝试:
#load()可以发现被截断的JPEG,但它会加载整个JPEG
#内存中的图像,这是一个DoS向量。见#3848和#18520。
image=image.open(文件)
#必须在构造函数之后立即调用verify()。
image.verify()
#注释,以便子类可以重用它进行自己的验证
f、 图像=图像
#Pillow未检测到所有格式的MIME类型。在那些
#案例,内容类型将为无。
f、 content\u type=Image.MIME.get(Image.format)
除作为exc的例外情况外:
#枕头无法将其识别为图像。
引发验证错误(
self.error_消息['invalid_image'],
代码=“无效的\u图像”,
)来自exc
如果hasattr(f,“seek”)和callable(f.seek):
f、 搜索(0)
返回f
如果您看到文档,这是正在运行的代码

Image.verify()

验证文件的内容。对于从文件读取的数据,此方法尝试确定文件是否已损坏,而不实际解码图像数据。如果此方法发现任何问题,将引发适当的异常。如果使用此方法后需要加载图像,则必须重新打开图像文件

因此,基本上它是试图确定文件是否已损坏。可能是在验证您的
mp4
文件,这就是为什么没有例外。如果需要更严格的验证,则需要使用
magic
或其他库来确定文件类型。请参见下文,以便了解相同的信息


Django并不急于验证。您应该调用
obj.full\u clean()
来运行所有验证。这主要是出于性能方面的原因。@WillemVanOnsem但是当您调用
save()
时,它不应该验证它吗?不,这正是问题所在。出于性能原因,验证器不使用
.save()
运行。但是,
ModelForm
将调用清理函数(当然,除非您重写该函数)。@WillemVanOnsem
full\u clean()
不执行任何操作。仍然没有验证错误。