Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions members_map/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import hashlib
import logging
import os
import secrets
from functools import cache
from pathlib import Path

from flask import Flask

Expand All @@ -27,6 +30,17 @@ def create_app(config: dict | None = None) -> Flask:
db.init_app(app)
app.register_blueprint(views.bp)

@cache
def static_version(filename: str) -> str:
path = Path(app.static_folder) / filename
return hashlib.sha256(path.read_bytes()).hexdigest()[:12]

@app.url_defaults
def version_static_urls(endpoint: str, values: dict) -> None:
# Cloudflare caches /static/ for hours, so changed files need new URLs
if endpoint == "static" and "v" not in values:
values["v"] = static_version(values["filename"])

@app.after_request
def set_referrer_policy(response):
# OpenStreetMap's tile servers refuse requests without a Referer
Expand Down
12 changes: 12 additions & 0 deletions tests/test_views.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import base64
import hashlib
import json
from pathlib import Path

import pytest

Expand Down Expand Up @@ -63,6 +65,16 @@ def test_tiles_use_https_osm_without_subdomains(client):
assert "{s}" not in js


def test_static_urls_are_versioned_by_content(app, client):
css = (Path(app.static_folder) / "style.css").read_bytes()
version = hashlib.sha256(css).hexdigest()[:12]

html = client.get("/").text

assert f"/static/style.css?v={version}" in html
assert "/static/vendor/leaflet.js?v=" in html


def test_referrer_policy_header_sends_origin(client):
response = client.get("/")

Expand Down
Loading