Skip to content

Commit 4ed0337

Browse files
committed
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
1 parent 942efac commit 4ed0337

2 files changed

Lines changed: 18 additions & 7 deletions

File tree

ietf/submit/parsers/plain_parser.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,15 @@ def parse_max_size(self):
3232
def parse_file_charset(self):
3333
import magic
3434
self.fd.file.seek(0)
35-
m = magic.open(magic.MAGIC_MIME)
36-
m.load()
37-
filetype = m.buffer(self.fd.file.read())
35+
if hasattr(magic, "open"):
36+
m = magic.open(magic.MAGIC_MIME)
37+
m.load()
38+
filetype = m.buffer(content)
39+
else:
40+
m = magic.Magic()
41+
m.cookie = magic.magic_open(magic.MAGIC_NONE | magic.MAGIC_MIME | magic.MAGIC_MIME_ENCODING)
42+
magic.magic_load(m.cookie, None)
43+
filetype = m.from_buffer(content)
3844
if not 'ascii' in filetype:
3945
self.parsed_info.add_error('A plain text document must be submitted.')
4046

ietf/utils/textupload.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,15 @@ def get_cleaned_text_file_content(uploaded_file):
1818

1919
# try to fixup encoding
2020
import magic
21-
m = magic.open(magic.MAGIC_MIME)
22-
m.load()
23-
24-
filetype = m.buffer(content) # should look like "text/plain; charset=us-ascii"
21+
if hasattr(magic, "open"):
22+
m = magic.open(magic.MAGIC_MIME)
23+
m.load()
24+
filetype = m.buffer(content)
25+
else:
26+
m = magic.Magic()
27+
m.cookie = magic.magic_open(magic.MAGIC_NONE | magic.MAGIC_MIME | magic.MAGIC_MIME_ENCODING)
28+
magic.magic_load(m.cookie, None)
29+
filetype = m.from_buffer(content)
2530

2631
if not filetype.startswith("text"):
2732
raise django.forms.ValidationError("Uploaded file does not appear to be a text file.")

0 commit comments

Comments
 (0)