From 7bb1e586252d75d66e93006b2e6287baf820cb07 Mon Sep 17 00:00:00 2001 From: Brian Moe <brian.moe@ligo.org> Date: Thu, 31 Jan 2013 13:26:29 -0600 Subject: [PATCH] Mimetypes for file downloads. Issue #713 https://bugs.ligo.org/redmine/issues/713 --- gracedb/api.py | 8 ++++++-- utils/vfile.py | 20 +++++++++++++++++++- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/gracedb/api.py b/gracedb/api.py index 1717448c3..6c43d4250 100644 --- a/gracedb/api.py +++ b/gracedb/api.py @@ -698,8 +698,12 @@ class Files(APIView): response = HttpResponseNotFound("File not readable") elif os.path.isfile(filepath): # get an actual file. - response = HttpResponse(open(filepath, "r"), content_type="application/octet-stream") - response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(filename) + content_type, encoding = VersionedFile.guess_mimetype(filepath) + content_type = content_type or "application/octet-stream" + # XXX encoding should probably not be ignored. + response = HttpResponse(open(filepath, "r"), content_type=content_type) + if content_type == "application/octet-stream": + response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(filename) elif not filename: # Get list of files w/urls. rv = {} diff --git a/utils/vfile.py b/utils/vfile.py index 3c6d4c502..e6020db98 100644 --- a/utils/vfile.py +++ b/utils/vfile.py @@ -4,7 +4,7 @@ import tempfile import logging import errno import shutil - +import mimetypes class VersionedFile(file): """Open a versioned file. @@ -165,3 +165,21 @@ class VersionedFile(file): # XXX file does not have a __del__ method. Should we? if not self.closed: self.close() + + @staticmethod + def guess_mimetype(filename): + TEXT_EXTENSIONS = ['.log'] + filename = VersionedFile.basename(filename) + content_type, encoding = mimetypes.guess_type(filename) + if content_type is None and '.' in filename: + for ext in TEXT_EXTENSIONS: + if filename.endswith(ext): + content_type = 'text/plain' + break + return content_type, encoding + + @staticmethod + def basename(filename): + if ',' in filename: + filename = filename.split(',')[0] + return os.path.basename(filename) -- GitLab