Skip to content

Commit 8da2bbc

Browse files
authored
Merge pull request #2 from realpython/claude/project-thread-pm5duv
Version static URLs so Cloudflare serves the new CSS
2 parents 22129f0 + dc7b2ad commit 8da2bbc

2 files changed

Lines changed: 26 additions & 0 deletions

File tree

‎members_map/__init__.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1+
import hashlib
12
import logging
23
import os
34
import secrets
5+
from functools import cache
6+
from pathlib import Path
47

58
from 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

‎tests/test_views.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import base64
2+
import hashlib
23
import json
4+
from pathlib import Path
35

46
import 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+
6678
def test_referrer_policy_header_sends_origin(client):
6779
response = client.get("/")
6880

0 commit comments

Comments
 (0)