From 3ff320950e74fecd89bdaa4fb7609762f2806929 Mon Sep 17 00:00:00 2001 From: Antoine Augusti Date: Mon, 26 Apr 2021 08:40:55 -0400 Subject: [PATCH 1/2] feat: set cache headers for static assets --- app/__init__.py | 13 +++++++++---- app/config.py | 1 - app/templates/main_template.html | 6 +++--- app/templates/notify_template.html | 2 +- app/templates/views/signedout.html | 4 ++-- tests/app/main/views/test_headers.py | 17 +++++++++++++++++ tests/app/main/views/test_index.py | 5 ++--- 7 files changed, 34 insertions(+), 14 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 4e34ff5b5b..3956b83ce6 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -6,6 +6,7 @@ from functools import partial from numbers import Number from time import monotonic +from urllib.parse import urljoin import timeago from flask import ( @@ -134,7 +135,7 @@ def create_app(application): application.config.from_object(configs[notify_environment]) asset_fingerprinter._cdn_domain = application.config['ASSET_DOMAIN'] - asset_fingerprinter._asset_root = application.config['ASSET_PATH'] + asset_fingerprinter._asset_root = urljoin(application.config['ADMIN_BASE_URL'], application.config['ASSET_PATH']) application.config["BABEL_DEFAULT_LOCALE"] = "en" babel = Babel(application) @@ -257,7 +258,6 @@ def record_start_time(): @application.context_processor def inject_global_template_variables(): return { - 'asset_path': application.config['ASSET_PATH'], 'header_colour': application.config['HEADER_COLOUR'], 'asset_url': asset_fingerprinter.get_url, 'asset_s3_url': asset_fingerprinter.get_s3_url, @@ -648,8 +648,13 @@ def useful_headers_after_request(response): )) if 'Cache-Control' in response.headers: del response.headers['Cache-Control'] - response.headers.add( - 'Cache-Control', 'no-store, no-cache, private, must-revalidate') + # Cache static assets (CSS, JS, images) for a long time + # as they have unique hashes thanks to the asset + # fingerprinter + if request.url.startswith(asset_fingerprinter._asset_root): + response.headers.add('Cache-Control', 'public, max-age=31536000, immutable') + else: + response.headers.add('Cache-Control', 'no-store, no-cache, private, must-revalidate') for key, value in response.headers: response.headers[key] = SanitiseASCII.encode(value) return response diff --git a/app/config.py b/app/config.py index 6f42ffd673..52637cf06b 100644 --- a/app/config.py +++ b/app/config.py @@ -143,7 +143,6 @@ class Test(Development): ANTIVIRUS_API_HOST = 'https://test-antivirus' ANTIVIRUS_API_KEY = 'test-antivirus-secret' ASSET_DOMAIN = 'static.example.com' - ASSET_PATH = 'https://static.example.com/' class Production(Config): diff --git a/app/templates/main_template.html b/app/templates/main_template.html index 8baf564795..82f06f7b96 100644 --- a/app/templates/main_template.html +++ b/app/templates/main_template.html @@ -12,13 +12,13 @@ @@ -34,7 +34,7 @@