From 20abe4b9036823ec8faeffeabc601fc287aa54dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Sch=C3=A4fer?= Date: Sat, 22 Jan 2022 15:02:06 +0100 Subject: [PATCH] Add Vary: Accept-Language to all pages using that information It was found during testing that some user agents cache aggressively even between switches of the UI language. To properly indicate that the pages actually depend on that information, we add the correct Vary header. Fixes #106. --- snikket_web/infra.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/snikket_web/infra.py b/snikket_web/infra.py index c5e9ef0..890c160 100644 --- a/snikket_web/infra.py +++ b/snikket_web/infra.py @@ -8,6 +8,7 @@ import quart.flask_patch # noqa:F401 from quart import ( current_app, request, + g, ) import flask_babel @@ -34,6 +35,9 @@ BYTE_UNIT_SCALE_MAP = [ @babel.localeselector # type:ignore def selected_locale() -> str: + # Needs mypy ignore because this is a free-for-all object and has no + # publicly known attributes. + g.language_header_accessed = True # type: ignore selected = request.accept_languages.best_match( current_app.config['LANGUAGES'] ) or current_app.config['LANGUAGES'][0] @@ -68,6 +72,12 @@ def format_bytes(n: float) -> str: return "{} {}".format(n, unit) +def add_vary_language_header(resp: quart.Response) -> quart.Response: + if getattr(g, "language_header_accessed", False): + resp.vary.add("Accept-Language") + return resp + + def init_templating(app: quart.Quart) -> None: app.template_filter("repr")(repr) app.template_filter("format_datetime")(flask_babel.format_datetime) @@ -78,6 +88,7 @@ def init_templating(app: quart.Quart) -> None: app.template_filter("format_bytes")(format_bytes) app.template_filter("flatten")(flatten) app.template_filter("circle_name")(circle_name) + app.after_request(add_vary_language_header) def generate_error_id() -> str: