From d1d10ceb794fa94ee5c8ae1c56b4ce7e8cbe9ad8 Mon Sep 17 00:00:00 2001 From: Benjamin Dauvergne Date: Fri, 23 Mar 2018 14:19:12 +0100 Subject: [PATCH] models: handle ENOENT from file-magic (#22745) magic.Magic.file() does not return None or raise an exception on a missing file, it just return the string "cannot open ...". --- fargo/fargo/models.py | 12 ++---------- fargo/fargo/utils.py | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/fargo/fargo/models.py b/fargo/fargo/models.py index f620d3c..1774359 100644 --- a/fargo/fargo/models.py +++ b/fargo/fargo/models.py @@ -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 diff --git a/fargo/fargo/utils.py b/fargo/fargo/utils.py index 643f931..0ce7737 100644 --- a/fargo/fargo/utils.py +++ b/fargo/fargo/utils.py @@ -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,19 @@ 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: + raise Exception + 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 -- 2.14.2