File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import hashlib
12import logging
23import os
34import secrets
5+ from functools import cache
6+ from pathlib import Path
47
58from flask import Flask
69
@@ -27,6 +30,17 @@ def create_app(config: dict | None = None) -> Flask:
2730 db .init_app (app )
2831 app .register_blueprint (views .bp )
2932
33+ @cache
34+ def static_version (filename : str ) -> str :
35+ path = Path (app .static_folder ) / filename
36+ return hashlib .sha256 (path .read_bytes ()).hexdigest ()[:12 ]
37+
38+ @app .url_defaults
39+ def version_static_urls (endpoint : str , values : dict ) -> None :
40+ # Cloudflare caches /static/ for hours, so changed files need new URLs
41+ if endpoint == "static" and "v" not in values :
42+ values ["v" ] = static_version (values ["filename" ])
43+
3044 @app .after_request
3145 def set_referrer_policy (response ):
3246 # OpenStreetMap's tile servers refuse requests without a Referer
Original file line number Diff line number Diff line change 11import base64
2+ import hashlib
23import json
4+ from pathlib import Path
35
46import pytest
57
@@ -63,6 +65,16 @@ def test_tiles_use_https_osm_without_subdomains(client):
6365 assert "{s}" not in js
6466
6567
68+ def test_static_urls_are_versioned_by_content (app , client ):
69+ css = (Path (app .static_folder ) / "style.css" ).read_bytes ()
70+ version = hashlib .sha256 (css ).hexdigest ()[:12 ]
71+
72+ html = client .get ("/" ).text
73+
74+ assert f"/static/style.css?v={ version } " in html
75+ assert "/static/vendor/leaflet.js?v=" in html
76+
77+
6678def test_referrer_policy_header_sends_origin (client ):
6779 response = client .get ("/" )
6880
You can’t perform that action at this time.
0 commit comments