-
Notifications
You must be signed in to change notification settings - Fork 16
/
validators.py
54 lines (37 loc) · 1.58 KB
/
validators.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import mimetypes
import magic # pylint: disable=E0401
from django.core.exceptions import ValidationError
from django.utils.translation import gettext
from django.template.defaultfilters import filesizeformat
class RestrictedFileValidator:
def __init__(self, max_upload_size):
self.max_upload_size = max_upload_size
def __call__(self, data):
if data.size > self.max_upload_size:
raise ValidationError(
gettext('Please keep filesize under {max}. Current filesize {current}').format(
max=filesizeformat(self.max_upload_size),
current=filesizeformat(data.size)
)
)
else:
return data
class AllowedContentTypesByFilenameFileValidator:
def __init__(self, content_types):
self.content_types = content_types
def __call__(self, data):
extension_mime_type = mimetypes.guess_type(data.name)[0]
if extension_mime_type not in self.content_types:
raise ValidationError(gettext('Extension of file name is not allowed'))
return data
class AllowedContentTypesByContentFileValidator:
def __init__(self, content_types):
self.content_types = content_types
def __call__(self, data):
data.open()
with magic.Magic(flags=magic.MAGIC_MIME_TYPE) as m:
mime_type = m.id_buffer(data.read(2048))
data.seek(0)
if mime_type not in self.content_types:
raise ValidationError(gettext('File content was evaluated as not supported file type'))
return data