0001-models-handle-ENOENT-from-file-magic-22745.patch
fargo/fargo/models.py | ||
---|---|---|
5 | 5 |
import re |
6 | 6 |
import threading |
7 | 7 | |
8 |
try: |
|
9 |
import magic |
|
10 |
except ImportError: |
|
11 |
magic = None |
|
12 | ||
13 | 8 |
from django.conf import settings |
14 | 9 |
from django.core.urlresolvers import reverse |
15 | 10 |
from django.db import models |
... | ... | |
181 | 176 |
'''Create content_hash if new''' |
182 | 177 |
if not self.content_hash: |
183 | 178 |
self.content_hash = utils.sha256_of_file(self.content) |
184 |
if magic is not None: |
|
185 |
magic_object = magic.open(magic.MIME) |
|
186 |
magic_object.load() |
|
187 |
self.mime_type = magic_object.file(str(self.content.file.name)).split(';')[0] |
|
188 |
magic_object.close() |
|
179 |
if not self.mime_type: |
|
180 |
self.mime_type = utils.get_mime_type(self.content.file.name) or '' |
|
189 | 181 |
super(Document, self).save(*args, **kwargs) |
190 | 182 | |
191 | 183 |
@property |
fargo/fargo/utils.py | ||
---|---|---|
1 | 1 |
import hashlib |
2 | ||
2 | 3 |
from django.utils.timezone import utc |
4 |
from django.utils.encoding import smart_bytes |
|
5 | ||
6 |
try: |
|
7 |
import magic |
|
8 |
except ImportError: |
|
9 |
magic = None |
|
3 | 10 | |
4 | 11 | |
5 | 12 |
def to_isodate(dt): |
... | ... | |
18 | 25 |
for chunk in f.chunks(): |
19 | 26 |
hasher.update(chunk) |
20 | 27 |
return hasher.hexdigest() |
28 | ||
29 | ||
30 |
def get_mime_type(path): |
|
31 |
if magic is None: |
|
32 |
raise Exception |
|
33 |
return None |
|
34 | ||
35 |
magic_object = magic.open(magic.MIME) |
|
36 |
magic_object.load() |
|
37 |
mime_type = magic_object.file(smart_bytes(path)) |
|
38 |
magic_object.close() |
|
39 |
if mime_type: |
|
40 |
mime_type = mime_type.split(';')[0] |
|
41 |
if mime_type.startswith('cannot open'): |
|
42 |
mime_type = None |
|
43 |
return mime_type |
|
21 |
- |