models: handle ENOENT from file-magic (fixes #22745)

magic.Magic.file() does not return None or raise an exception on a
missing file, it just return the string "cannot open ...".
This commit is contained in:
Benjamin Dauvergne 2018-03-23 14:19:12 +01:00
parent 666fe66494
commit a102c7d78e
2 changed files with 24 additions and 10 deletions

View File

@ -5,11 +5,6 @@ import os
import re
import threading
try:
import magic
except ImportError:
magic = None
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
@ -181,11 +176,8 @@ class Document(models.Model):
'''Create content_hash if new'''
if not self.content_hash:
self.content_hash = utils.sha256_of_file(self.content)
if magic is not None:
magic_object = magic.open(magic.MIME)
magic_object.load()
self.mime_type = magic_object.file(str(self.content.file.name)).split(';')[0]
magic_object.close()
if not self.mime_type:
self.mime_type = utils.get_mime_type(self.content.file.name) or ''
super(Document, self).save(*args, **kwargs)
@property

View File

@ -1,5 +1,12 @@
import hashlib
from django.utils.timezone import utc
from django.utils.encoding import smart_bytes
try:
import magic
except ImportError:
magic = None
def to_isodate(dt):
@ -18,3 +25,18 @@ def sha256_of_file(f):
for chunk in f.chunks():
hasher.update(chunk)
return hasher.hexdigest()
def get_mime_type(path):
if magic is None:
return None
magic_object = magic.open(magic.MIME)
magic_object.load()
mime_type = magic_object.file(smart_bytes(path))
magic_object.close()
if mime_type:
mime_type = mime_type.split(';')[0]
if mime_type.startswith('cannot open'):
mime_type = None
return mime_type