Browse code

Merge pull request #14 from ksperling/master

Guess MIME types using python-magic

Michal Ludvig authored on 2011/11/21 11:24:18
Showing 1 changed files
... ...
@@ -27,6 +27,29 @@ from ACL import ACL, GranteeLogDelivery
27 27
 from AccessLog import AccessLog
28 28
 from S3Uri import S3Uri
29 29
 
30
+try:
31
+    import magic
32
+    try:
33
+        ## https://github.com/ahupp/python-magic
34
+        magic_ = magic.Magic(mime=True)
35
+        def mime_magic(file):
36
+            return magic_.from_file(file)
37
+    except AttributeError:
38
+        ## Older python-magic versions
39
+        magic_ = magic.open(magic.MAGIC_MIME)
40
+        magic_.load()
41
+        def mime_magic(file):
42
+            return magic_.file(file)
43
+except ImportError:
44
+    magic_warned = False
45
+    def mime_magic(file):
46
+        global magic_warned
47
+        if (not magic_warned):
48
+            warning("python-magic is not available, guessing MIME types based on file extensions only")
49
+            magic_warned = True
50
+        return mimetypes.guess_type(file)[0]
51
+
52
+
30 53
 __all__ = []
31 54
 class S3Request(object):
32 55
     def __init__(self, s3, method_string, resource, headers, params = {}):
... ...
@@ -328,7 +351,7 @@ class S3(object):
328 328
         headers["content-length"] = size
329 329
         content_type = self.config.mime_type
330 330
         if not content_type and self.config.guess_mime_type:
331
-            content_type = mimetypes.guess_type(filename)[0]
331
+            content_type = mime_magic(filename)
332 332
         if not content_type:
333 333
             content_type = self.config.default_mime_type
334 334
         debug("Content-Type set to '%s'" % content_type)