From 7ad649e3b79c20d9cbb783148e659824c46fbf8c Mon Sep 17 00:00:00 2001 From: Forest Date: Fri, 31 Oct 2014 23:05:19 -0700 Subject: [PATCH] Guess mime type with python-magic if available. Fixes #1514. --- pelican/server.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/pelican/server.py b/pelican/server.py index 0a8dc1b6..60252e1f 100644 --- a/pelican/server.py +++ b/pelican/server.py @@ -12,6 +12,11 @@ try: except ImportError: import socketserver # NOQA +try: + from magic import from_file as magic_from_file +except ImportError: + magic_from_file = None + PORT = len(sys.argv) in (2, 3) and int(sys.argv[1]) or 8000 SERVER = len(sys.argv) == 3 and sys.argv[2] or "" SUFFIXES = ['', '.html', '/index.html'] @@ -39,6 +44,18 @@ class ComplexHTTPRequestHandler(srvmod.SimpleHTTPRequestHandler): logging.warning("Unable to find `%s` or variations.", self.original_path) + def guess_type(self, path): + """Guess at the mime type for the specified file. + """ + mimetype = srvmod.SimpleHTTPRequestHandler.guess_type(self, path) + + # If the default guess is too generic, try the python-magic library + if mimetype == 'application/octet-stream' and magic_from_file: + mimetype = magic_from_file(path, mime=True) + + return mimetype + + Handler = ComplexHTTPRequestHandler socketserver.TCPServer.allow_reuse_address = True