From 4ed0337cae133b0bf136165f8416cca87b08bd7d Mon Sep 17 00:00:00 2001 From: Henrik Levkowetz Date: Thu, 25 Jul 2013 14:45:01 +0000 Subject: [PATCH] Made the code which uses the 'magic' module to determine file type and encoding work with both the old and new interface to python-magic. - Legacy-Id: 5876 --- ietf/submit/parsers/plain_parser.py | 12 +++++++++--- ietf/utils/textupload.py | 13 +++++++++---- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/ietf/submit/parsers/plain_parser.py b/ietf/submit/parsers/plain_parser.py index 1db738e69..10cf09aab 100644 --- a/ietf/submit/parsers/plain_parser.py +++ b/ietf/submit/parsers/plain_parser.py @@ -32,9 +32,15 @@ class PlainParser(FileParser): def parse_file_charset(self): import magic self.fd.file.seek(0) - m = magic.open(magic.MAGIC_MIME) - m.load() - filetype = m.buffer(self.fd.file.read()) + if hasattr(magic, "open"): + m = magic.open(magic.MAGIC_MIME) + m.load() + filetype = m.buffer(content) + else: + m = magic.Magic() + m.cookie = magic.magic_open(magic.MAGIC_NONE | magic.MAGIC_MIME | magic.MAGIC_MIME_ENCODING) + magic.magic_load(m.cookie, None) + filetype = m.from_buffer(content) if not 'ascii' in filetype: self.parsed_info.add_error('A plain text document must be submitted.') diff --git a/ietf/utils/textupload.py b/ietf/utils/textupload.py index eeb6d141d..1a4dbe705 100644 --- a/ietf/utils/textupload.py +++ b/ietf/utils/textupload.py @@ -18,10 +18,15 @@ def get_cleaned_text_file_content(uploaded_file): # try to fixup encoding import magic - m = magic.open(magic.MAGIC_MIME) - m.load() - - filetype = m.buffer(content) # should look like "text/plain; charset=us-ascii" + if hasattr(magic, "open"): + m = magic.open(magic.MAGIC_MIME) + m.load() + filetype = m.buffer(content) + else: + m = magic.Magic() + m.cookie = magic.magic_open(magic.MAGIC_NONE | magic.MAGIC_MIME | magic.MAGIC_MIME_ENCODING) + magic.magic_load(m.cookie, None) + filetype = m.from_buffer(content) if not filetype.startswith("text"): raise django.forms.ValidationError("Uploaded file does not appear to be a text file.")