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
9 changes: 8 additions & 1 deletion app.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import dash_bootstrap_components as dbc
from dash_extensions.enrich import DashProxy, ServersideOutputTransform
from flask import send_file
from flask import jsonify, send_file

from pages.lib.basemap import CARTO_STYLE_ROUTE, keyed_style

app = DashProxy(
__name__,
Expand Down Expand Up @@ -29,6 +31,11 @@ def serve_locations_geojson():
)


@app.server.route(CARTO_STYLE_ROUTE)
def serve_carto_style():
return jsonify(keyed_style()), {"Cache-Control": "public, max-age=86400"}


app.index_string = """<!DOCTYPE html>
<html lang="en-US">
<head>
Expand Down
50 changes: 50 additions & 0 deletions assets/carto_basemap.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Adds the CARTO vector basemap, drawn by MapLibre GL, to every Leaflet map
// whose container has the "carto-basemap" class (set via dl.Map(className=...)).
// MapLibre and its Leaflet plugin are only loaded once such a map is created.
// dash-leaflet's own "load" event fires before custom handlers are bound,
// so we use a Leaflet init hook instead.
(function () {
const MAPLIBRE = "https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl";
const PLUGIN = "https://cdn.jsdelivr.net/npm/@maplibre/maplibre-gl-leaflet@0.0.22/leaflet-maplibre-gl.js";
const STYLE = "/basemap/positron.json";
const ATTRIBUTION =
'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>' +
' contributors &copy; <a href="https://carto.com/">CARTO</a>';
let loading = null;

function loadScript(src) {
return new Promise(function (resolve, reject) {
const script = document.createElement("script");
script.src = src;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}

function loadMapLibre() {
if (!loading) {
const css = document.createElement("link");
css.rel = "stylesheet";
css.href = MAPLIBRE + ".css";
document.head.appendChild(css);
loading = loadScript(MAPLIBRE + ".js").then(function () {
return loadScript(PLUGIN);
});
}
return loading;
}

if (!window.L) {
return;
}
L.Map.addInitHook(function () {
const map = this;
if (!map.getContainer().classList.contains("carto-basemap")) {
return;
}
loadMapLibre().then(function () {
L.maplibreGL({ style: STYLE, attribution: ATTRIBUTION }).addTo(map);
});
});
})();
6 changes: 6 additions & 0 deletions assets/img/carto-logo.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
62 changes: 62 additions & 0 deletions pages/lib/basemap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""CARTO vector basemap: a copy of the Positron style with our API key on every URL.

CARTO requires the key on every style, tile, glyph and sprite request, but the
published style.json does not carry it. Both maps load the style from our own
route (see app.py), which serves the keyed copy built here.
"""

import functools
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit

import requests

from config import AppConfig

CARTO_STYLE_URL = "https://basemaps.cartocdn.com/gl/positron-gl-style/style.json"
# also hard-coded in assets/carto_basemap.js
CARTO_STYLE_ROUTE = "/basemap/positron.json"


def add_key(url: str, key: str) -> str:
"""Append the key to a cartocdn.com URL, keeping {placeholders} intact."""
if not key or "cartocdn.com" not in urlsplit(url).netloc:
return url
parts = urlsplit(url)
query = dict(parse_qsl(parts.query))
query["key"] = key
return urlunsplit(parts._replace(query=urlencode(query, safe="{}")))


def _fetch_json(url: str) -> dict:
response = requests.get(url, timeout=10)
response.raise_for_status()
return response.json()


def build_keyed_style(key: str, fetch=_fetch_json) -> dict:
"""Return the Positron style with the key added to all CARTO URLs."""
style = fetch(add_key(CARTO_STYLE_URL, key))
if not key:
return style

for name in ("sprite", "glyphs"):
if isinstance(style.get(name), str):
style[name] = add_key(style[name], key)

for source in style.get("sources", {}).values():
if "url" in source:
# inline the TileJSON so its tile URLs can carry the key too
tilejson = fetch(add_key(source.pop("url"), key))
for field in ("tiles", "minzoom", "maxzoom", "attribution", "bounds"):
if field in tilejson:
source.setdefault(field, tilejson[field])
if "tiles" in source:
source["tiles"] = [add_key(tile, key) for tile in source["tiles"]]

return style


@functools.lru_cache(maxsize=1)
def keyed_style() -> dict:
"""Keyed style, fetched from CARTO once per server process."""
return build_keyed_style(AppConfig.CARTO_API_KEY)
2 changes: 1 addition & 1 deletion pages/lib/charts_summary.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def world_map(meta):
}
)

fig = px.scatter_mapbox(
fig = px.scatter_map(
lat_long_df,
lat="Lat",
lon="Long",
Expand Down
36 changes: 21 additions & 15 deletions pages/lib/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,35 @@
from dash import html, dcc
import dash_mantine_components as dmc

from config import AppConfig, UnitSystem
from config import UnitSystem
from pages.lib.basemap import CARTO_STYLE_ROUTE
from pages.lib.global_scheme import fig_config, month_lst
from pages.lib.global_variables import Variables, VariableInfo


def apply_carto_basemap(fig):
"""Apply the Carto Positron basemap, authenticated with our API key."""
fig.update_layout(
mapbox_style="white-bg",
mapbox_layers=[
{
"below": "traces",
"sourcetype": "raster",
"sourceattribution": "© OpenStreetMap contributors, © CARTO",
"source": [
f"https://basemaps.cartocdn.com/rastertiles/light_all/{{z}}/{{x}}/{{y}}.png?key={AppConfig.CARTO_API_KEY}"
],
}
],
)
"""Apply the Carto Positron vector basemap, served with our API key."""
fig.update_layout(map_style=CARTO_STYLE_ROUTE)
return fig


def carto_logo_badge():
"""CARTO logo linked to carto.com, overlaid on the bottom left of a map."""
return html.A(
html.Img(src="/assets/img/carto-logo.svg", alt="CARTO", height=20),
href="https://carto.com/",
target="_blank",
rel="noopener",
style={
"position": "absolute",
"bottom": 8,
"left": 8,
"zIndex": 1000,
"lineHeight": 0,
},
)


def code_timer(func):
"""Print the runtime of the decorated function"""

Expand Down
19 changes: 7 additions & 12 deletions pages/select.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
from pages.lib.extract_df import create_df, get_data, get_location_info
from pages.lib.global_variables import Variables
from pages.lib.global_element_ids import ElementIds
from config import AppConfig, PageUrls, PageInfo
from pages.lib.utils import get_default_global_filter_store_data
from config import PageUrls, PageInfo
from pages.lib.utils import carto_logo_badge, get_default_global_filter_store_data

dash.register_page(
__name__,
Expand Down Expand Up @@ -99,18 +99,12 @@ def layout():
id="map-container",
center=[20, 0],
zoom=2,
minZoom=2,
maxBounds=[[-85, -180], [85, 180]],
maxBoundsViscosity=1,
style={"height": "650px", "width": "100%"},
className="carto-basemap", # see assets/carto_basemap.js
children=[
dl.TileLayer(
url=(
"https://basemaps.cartocdn.com/rastertiles/light_all"
f"/{{z}}/{{x}}/{{y}}{{r}}.png?key={AppConfig.CARTO_API_KEY}"
),
attribution=(
'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
' contributors &copy; <a href="https://carto.com/">CARTO</a>'
),
),
dl.GeoJSON(
id=ElementIds.TAB_ONE_MAP,
url=_GEO_URL,
Expand All @@ -121,6 +115,7 @@ def layout():
),
],
),
carto_logo_badge(),
dmc.Autocomplete(
id=ElementIds.TAB_ONE_MAP_SEARCH,
placeholder="Search city or station...",
Expand Down
13 changes: 10 additions & 3 deletions pages/summary.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from pages.lib.global_id_buttons import IdButtons
from pages.lib.global_tab_names import TabNames
from pages.lib.utils import (
carto_logo_badge,
generate_chart_name,
generate_units,
generate_units_degree,
Expand Down Expand Up @@ -225,9 +226,15 @@ def update_layout(si_ip):
)
def update_map(meta):
"""Update the contents of tab two. Passing in the general info (df, meta)."""
return dcc.Graph(
config=generate_chart_name(TabNames.MAP, meta),
figure=world_map(meta),
return dmc.Box(
pos="relative",
children=[
dcc.Graph(
config=generate_chart_name(TabNames.MAP, meta),
figure=world_map(meta),
),
carto_logo_badge(),
],
)


Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ dependencies = [
"kgcpy==1.1.8",
"numpy==1.26.3",
"pandas==2.2.0",
"plotly==5.18.0",
"plotly==5.24.1",
"pvlib==0.9.1",
"pythermalcomfort==2.9.1",
"requests==2.32.4",
Expand Down
2 changes: 2 additions & 0 deletions pytest.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[pytest]
pythonpath = .
58 changes: 58 additions & 0 deletions tests/test_basemap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
from pages.lib.basemap import CARTO_STYLE_URL, add_key, build_keyed_style

TILES = "https://tiles.basemaps.cartocdn.com/v/1/vectortiles/carto.streets/v2/{z}/{x}/{y}.mvt"


def fake_fetch(responses):
"""Return a fetch stub that serves canned JSON by URL (ignoring the query)."""

def fetch(url):
return responses[url.split("?")[0]]

return fetch


def style(**sources):
return {
"sprite": "https://tiles.basemaps.cartocdn.com/v/1/gl/positron-gl-style/sprite",
"glyphs": "https://tiles.basemaps.cartocdn.com/v/1/fonts/{fontstack}/{range}.pbf",
"sources": sources,
"layers": [],
}


def test_add_key_keeps_placeholders_and_skips_other_hosts():
assert add_key(TILES, "K") == TILES + "?key=K"
assert add_key("https://example.com/a.json", "K") == "https://example.com/a.json"
assert add_key(TILES, "") == TILES


def test_key_added_to_sprite_glyphs_and_tiles():
fetch = fake_fetch({CARTO_STYLE_URL: style(streets={"tiles": [TILES]})})
result = build_keyed_style("K", fetch)

assert result["sprite"].endswith("/sprite?key=K")
assert result["glyphs"].endswith("/{fontstack}/{range}.pbf?key=K")
assert result["sources"]["streets"]["tiles"] == [TILES + "?key=K"]


def test_tilejson_source_is_inlined_with_key():
tilejson_url = "https://tiles.basemaps.cartocdn.com/tiles.json"
fetch = fake_fetch(
{
CARTO_STYLE_URL: style(streets={"type": "vector", "url": tilejson_url}),
tilejson_url: {"tiles": [TILES], "maxzoom": 14},
}
)
source = build_keyed_style("K", fetch)["sources"]["streets"]

assert "url" not in source
assert source["tiles"] == [TILES + "?key=K"]
assert source["maxzoom"] == 14


def test_no_key_returns_style_unchanged():
original = style(streets={"tiles": [TILES]})
fetch = fake_fetch({CARTO_STYLE_URL: original})

assert build_keyed_style("", fetch) == style(streets={"tiles": [TILES]})
10 changes: 5 additions & 5 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading