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
This commit is contained in:
Henrik Levkowetz 2013-07-25 14:45:01 +00:00
parent 942efacb08
commit 4ed0337cae
2 changed files with 18 additions and 7 deletions

View file

@ -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.')

View file

@ -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.")