From a9b8e4b425322d52bf07dfd0ea146f6ee1b7c315 Mon Sep 17 00:00:00 2001 From: "bool.dev" Date: Thu, 19 Nov 2015 15:49:55 +0530 Subject: [PATCH] Added a S3_FORCE_MIMETYPE config flag to always add the content-type header to s3 files. Added corresponding documentation for the flag. --- docs/index.rst | 2 ++ flask_s3.py | 24 ++++++++++++++---------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/docs/index.rst b/docs/index.rst index 6bd7458..d8ceea7 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -232,6 +232,8 @@ uploading assets to S3. `S3_GZIP` Compress all assets using GZIP and set the corresponding Content-Type and Content-Encoding headers on the S3 files. +`S3_FORCE_MIMETYPE` Always set the Content-Type header on the S3 files + irrespective of gzipping. Defaults to `False`. =========================== =================================================== .. _debug: http://flask.pocoo.org/docs/config/#configuration-basics diff --git a/flask_s3.py b/flask_s3.py index a4e80b9..c77dcbc 100644 --- a/flask_s3.py +++ b/flask_s3.py @@ -182,6 +182,7 @@ def _write_files(s3, app, static_url_loc, static_folder, files, bucket, ex_keys=None, hashes=None): """ Writes all the files inside a static folder to S3. """ should_gzip = app.config.get('S3_GZIP') + add_mime = app.config.get('S3_FORCE_MIMETYPE') new_hashes = [] static_folder_rel = _path_to_relative_url(static_folder) for file_path in files: @@ -215,15 +216,17 @@ def _write_files(s3, app, static_url_loc, static_folder, files, bucket, if should_gzip: h["content-encoding"] = "gzip" - if "content-type" not in h: - # When we use GZIP we have to explicitly set the content type - (mimetype, encoding) = mimetypes.guess_type(file_path, - False) - if mimetype: - h["content-type"] = mimetype - else: - logger.warn("Unable to detect mimetype for %s" % - file_path) + + if add_mime or should_gzip and "content-type" not in h: + # When we use GZIP we have to explicitly set the content type + # or if the mime flag is True + (mimetype, encoding) = mimetypes.guess_type(file_path, + False) + if mimetype: + h["content-type"] = mimetype + else: + logger.warn("Unable to detect mimetype for %s" % + file_path) with open(file_path) as fp: metadata, params = split_metadata_params(merge_two_dicts(app.config['S3_HEADERS'], h)) @@ -401,7 +404,8 @@ class FlaskS3(object): ('S3_FILEPATH_HEADERS', {}), ('S3_ONLY_MODIFIED', False), ('S3_URL_STYLE', 'host'), - ('S3_GZIP', False)] + ('S3_GZIP', False), + ('S3_FORCE_MIMETYPE', False)] for k, v in defaults: app.config.setdefault(k, v)