# HG changeset patch # User neko259 # Date 2015-10-17 09:12:48 # Node ID 224c8f015b7e9aa28de2092d473223c785b52c8b # Parent 3a697667d04336f2a41b679ae9bac0556e05ec3f Use python-magic to get file types diff --git a/boards/models/attachment/__init__.py b/boards/models/attachment/__init__.py --- a/boards/models/attachment/__init__.py +++ b/boards/models/attachment/__init__.py @@ -1,3 +1,5 @@ +import magic + from django.db import models from boards import utils @@ -15,7 +17,8 @@ class AttachmentManager(models.Manager): if len(existing) > 0: attachment = existing[0] else: - file_type = file.name.split(FILE_EXTENSION_DELIMITER)[-1].lower() + file_type = magic.from_buffer(file.chunks().__next__(), mime=True)\ + .decode().split('/')[-1] attachment = Attachment.objects.create( file=file, mimetype=file_type, hash=file_hash) diff --git a/boards/utils.py b/boards/utils.py --- a/boards/utils.py +++ b/boards/utils.py @@ -128,10 +128,14 @@ def validate_file_size(size: int): def get_upload_filename(model_instance, old_filename): # TODO Use something other than random number in file name + if hasattr(model_instance, 'file_type'): + extension = model_instance.file_type + else: + extension = old_filename.split(FILE_EXTENSION_DELIMITER)[-1:][0] new_name = '{}{}.{}'.format( str(int(time.mktime(time.gmtime()))), str(int(random() * 1000)), - old_filename.split(FILE_EXTENSION_DELIMITER)[-1:][0]) + extension) directory = UPLOAD_DIRS[type(model_instance).__name__] diff --git a/requirements.txt b/requirements.txt --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ +magic pytube requests adjacent