django - 如何使用 magic 来验证 Django 表单 clean 方法中的文件类型?

标签 django django-forms django-file-upload python-magic

我在 Django 中编写了一个带有 FileField 的电子邮件表单类。我想通过检查其 mimetype 来检查上传文件的类型。随后,我想将文件类型限制为 pdf、word 和打开的 Office 文档。

为此,我已经安装了 python-magic,并希望按照 python-magic 的规范检查文件类型:

mime = magic.Magic(mime=True)
file_mime_type = mime.from_file('address/of/file.txt')

但是,最近上传的文件在我的服务器上缺少地址。我也不知道 mime 对象有任何类似于“from_file_content”的方法来检查给定文件内容的 mime 类型。

在 Django 表单中使用 magic 来验证上传文件的文件类型的有效方法是什么?

最佳答案

斯坦描述了带有缓冲液的良好变体。不幸的是,这种方法的弱点是将文件读取到内存中。另一种选择是使用临时存储文件:

import tempfile
import magic
with tempfile.NamedTemporaryFile() as tmp:
    for chunk in form.cleaned_data['file'].chunks():
        tmp.write(chunk)
    print(magic.from_file(tmp.name, mime=True))

此外,您可能想检查文件大小:

if form.cleaned_data['file'].size < ...:
    print(magic.from_buffer(form.cleaned_data['file'].read()))
else:
    # store to disk (the code above)

Additionally :

Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).

所以你可能想像 so 那样处理它:

import os
tmp = tempfile.NamedTemporaryFile(delete=False)
try:
    for chunk in form.cleaned_data['file'].chunks():
        tmp.write(chunk)
    print(magic.from_file(tmp.name, mime=True))
finally:
    os.unlink(tmp.name)
    tmp.close()

此外,您可能想要seek(0)read()之后:

if hasattr(f, 'seek') and callable(f.seek):
    f.seek(0)

Where uploaded data is stored

关于django - 如何使用 magic 来验证 Django 表单 clean 方法中的文件类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8647401/

相关文章:

python-3.x - 单一 View 中的多模型表单集工厂

django 'thumbnail' 不是有效的标签库 :

django - 如何在 Django 中上传后访问文件?

django-forms - 使用文件字段编辑 Django 模型而不重新上传文件

python - 将 django cms 页面渲染为 json

Django 处理表单的方式?

python - django查询中的 "as_"是什么意思?

Django 图片上传表单无效

django - 如何将 HTML 输入到 Django 表单字段的帮助文本中?

Django 身份验证 : UserProfile vs. 贡献_to_class