在使用python magic上传之前验证文件

时间:2016-05-26 07:26:21

标签: django python-3.x python-magic

我正在使用python magic在上传之前验证文件,所以我遵循以下链接:

https://djangosnippets.org/snippets/3039/

validators.py文件:

from django.core.exceptions import ValidationError
import magic


class MimetypeValidator(object):
    def __init__(self, mimetypes):
        self.mimetypes = mimetypes

    def __call__(self, value):
        try:
            mime_byt = magic.from_buffer(value.read(1024), mime=True)
            mime = mime_byt.decode(encoding='UTF-8')
            if mime not in self.mimetypes:
                raise ValidationError('%s is not an acceptable file type' % value)
        except AttributeError as e:
            raise ValidationError('This value could not be validated for file type' % value)

这是我的form.py文件:

class FileForm(forms.ModelForm):
    file = forms.FileField(
        label='Select a File *',
        allow_empty_file=False,
        validators=[MimetypeValidator('application/pdf')],
        help_text='Max. Size - 25 MB')

    class Meta:
        model = File
        fields = ('file')

所以我可以使用这个python魔术逻辑上传pdf文件,但我也想允许上传图像tiff文件并将文件大小限制为25 MB。

如何使用python magic实现这一点?

1 个答案:

答案 0 :(得分:2)

您不需要任何库来执行此操作 - 您可以在表单上的clean方法中检查文件的上载大小:

def clean_file(self):
    file = self.cleaned_data['file']
    if file.size > 25000000:
        raise ValidationError('The file is too big')
    return file