Added support for several 'libmagic' packages
authorThierry Florac <tflorac@ulthar.net>
Sun, 21 May 2017 01:50:16 +0200
changeset 34 47dd5b37fab5
parent 33 bd1f5624dce8
child 35 57b510d3cbe4
Added support for several 'libmagic' packages
src/pyams_file/file.py
--- a/src/pyams_file/file.py	Tue Dec 27 15:40:04 2016 +0100
+++ b/src/pyams_file/file.py	Sun May 21 01:50:16 2017 +0200
@@ -196,13 +196,21 @@
 
 
 def get_magic_content_type(input):
-    """Get content-type based on magic library as *bytes*"""
+    """Get content-type based on magic library as *bytes*
+    
+    As libmagic bindings are provided via several 'magic' packages, we try them in order
+    """
     if magic is not None:
         if hasattr(input, 'seek'):
             input.seek(0)
         if hasattr(input, 'read'):
             input = input.read()
-        return magic.from_buffer(input, mime=True)
+        if hasattr(magic, 'detect_from_content'):
+            result = magic.detect_from_content(input)
+            if result:
+                return result.mime_type.encode()
+        elif hasattr(magic, 'from_buffer'):
+            return magic.from_buffer(input, mime=True)
     else:
         return None