Open Infrastructure Map, a view of infrastructure data in OpenStreetMap
Fixes
Russ Garrettab6238d6ab34
diff --git a/web-backend/src/charts/__init__.py b/web-backend/src/charts/__init__.pyindex 09467fa..7271c63 100644--- a/web-backend/src/charts/__init__.py+++ b/web-backend/src/charts/__init__.py@@ -2,6 +2,8 @@ import pandas as pdfrom bokeh.models import ColumnDataSource, HoverTool, NumeralTickFormatterfrom bokeh.palettes import Category10from bokeh.themes import Theme+from sqlalchemy.ext.asyncio import AsyncConnection+from sqlalchemy.sql import textfrom .util import figure, result_to_df@@ -30,9 +32,10 @@ theme = Theme()-async def line_length(database):- data = await database.fetch_all(- """SELECT date_trunc('week', time) AS date,+async def line_length(database: AsyncConnection):+ data = await database.execute(+ text(+ """SELECT date_trunc('week', time) AS date,avg((SELECT SUM(length) FROM stats.power_line WHERE time = a.time)) AS total_length,avg((SELECT SUM(length) FROM stats.power_line WHERE time = a.timeAND voltage IS NOT NULL)) AS with_voltage@@ -40,11 +43,12 @@ async def line_length(database):GROUP BY date_trunc('week', time)ORDER BY date_trunc('week', time)"""+ ))- data = result_to_df(data)+ df = result_to_df(data.fetchall())- cds = ColumnDataSource(data)+ cds = ColumnDataSource(df)p = figure(x_axis_type="datetime",@@ -99,9 +103,10 @@ def _plot_stacked_areas(p, data: pd.DataFrame, colors: dict[str, str], hover=Nonreturn p-async def plant_count(database):- data = await database.fetch_all(- """SELECT date_trunc('week', time) AS date, type, avg(total_count) AS total_count FROM (+async def plant_count(database: AsyncConnection):+ data = await database.execute(+ text(+ """SELECT date_trunc('week', time) AS date, type, avg(total_count) AS total_count FROM (SELECT time,CASEWHEN source IN ('solar') THEN 'Solar'@@ -117,11 +122,12 @@ async def plant_count(database):GROUP BY date_trunc('week', time), typeORDER BY date_trunc('week', time)"""+ ))- data = result_to_df(data)+ df = result_to_df(data.fetchall())- pivot_data = data.pivot(index="date", columns="type", values="total_count").fillna(0)+ pivot_data = df.pivot(index="date", columns="type", values="total_count").fillna(0)# Reorder columns to match the order in SOURCE_COLORSpivot_data = pivot_data[[key for key in SOURCE_COLORS.keys() if key in pivot_data]]@@ -152,9 +158,10 @@ async def plant_count(database):return p-async def plant_output(database):- data = await database.fetch_all(- """SELECT time AS date,+async def plant_output(database: AsyncConnection):+ data = await database.execute(+ text(+ """SELECT time AS date,CASEWHEN source IN ('solar') THEN 'Solar'WHEN source IN ('coal', 'gas', 'oil', 'diesel', 'nuclear') THEN 'Fossil Fuels'@@ -166,11 +173,12 @@ async def plant_output(database):FROM stats.power_plantGROUP BY time, typeORDER BY time"""+ ))- data = result_to_df(data)+ df = result_to_df(data.fetchall())- pivot_data = data.pivot(index="date", columns="type", values="total_output").fillna(0)+ pivot_data = df.pivot(index="date", columns="type", values="total_output").fillna(0)# Reorder columns to match the order in SOURCE_COLORSpivot_data = pivot_data[[key for key in SOURCE_COLORS.keys() if key in pivot_data]]@@ -201,9 +209,10 @@ async def plant_output(database):return p-async def substation_count(database):- data = await database.fetch_all(- """SELECT date_trunc('week', time) AS date,+async def substation_count(database: AsyncConnection):+ data = await database.execute(+ text(+ """SELECT date_trunc('week', time) AS date,avg((SELECT SUM(count) FROM stats.substation WHERE time = s.time)) AS total_count,avg((SELECT SUM(count) FROM stats.substation WHERE time = s.timeAND voltage IS NOT NULL)) AS with_voltage@@ -211,18 +220,19 @@ async def substation_count(database):GROUP BY date_trunc('week', time)ORDER BY date_trunc('week', time)"""+ ))- data = result_to_df(data)- cds = ColumnDataSource(data)+ df = result_to_df(data.fetchall())+ cds = ColumnDataSource(df)p = figure(x_axis_type="datetime",title="Substation count",- y_range=(0, data["total_count"].max() * 1.1),+ y_range=(0, df["total_count"].max() * 1.1),x_range=(pd.to_datetime("2014-01-01"),- data["date"].max() + pd.Timedelta(days=10),+ df["date"].max() + pd.Timedelta(days=10),),)p.yaxis.axis_label = "Count"diff --git a/web-backend/src/main.py b/web-backend/src/main.pyindex ccfef7b..34fcd7f 100644--- a/web-backend/src/main.py+++ b/web-backend/src/main.py@@ -26,6 +26,8 @@ async def lifespan(app: Starlette) -> AsyncGenerator[State]:db_engine.begin() as db,):yield {"http_client": client, "db": db}+ if db.in_transaction():+ await db.rollback()app = Starlette(diff --git a/web-backend/src/views/area.py b/web-backend/src/views/area.pyindex 8438486..02850da 100644--- a/web-backend/src/views/area.py+++ b/web-backend/src/views/area.py@@ -6,7 +6,7 @@ from bokeh.core.types import IDfrom bokeh.embed import json_itemfrom sqlalchemy import textfrom starlette.exceptions import HTTPException-from starlette.responses import RedirectResponse+from starlette.responses import RedirectResponse, Responsefrom starlette.routing import Routefrom .. import Request, charts@@ -115,12 +115,13 @@ async def plants_region(request: Request, region):@region_required@cache_for(hours=1)-async def plants_construction_region(request, region):+async def plants_construction_region(request: Request, region) -> Response:database = request.state["db"]gid = region["gid"]- plants = await database.fetch_all(- query="""SELECT osm_id, name, tags->'name:en' AS name_en, tags->'wikidata' AS wikidata,+ plants = await database.execute(+ text(+ """SELECT osm_id, name, tags->'name:en' AS name_en, tags->'wikidata' AS wikidata,tags->'plant:method' AS method, tags->'operator' AS operator,tags->'start_date' AS start_date,convert_power(output) AS output,@@ -130,8 +131,9 @@ async def plants_construction_region(request, region):(SELECT ST_Transform(geom, 3857) FROM countries.country_eez WHERE gid = :gid),geometry)AND tags -> 'construction:power' IS NOT NULL- ORDER BY convert_power(output) DESC NULLS LAST, name ASC NULLS LAST """,- values={"gid": gid},+ ORDER BY convert_power(output) DESC NULLS LAST, name ASC NULLS LAST """+ ),+ {"gid": gid},)return render_template(@@ -147,37 +149,41 @@ async def plants_construction_region(request, region):@cache_for(hours=1)-async def stats_object(request):+async def stats_object(request: Request) -> Response:database = request.state["db"]try:id = int(request.path_params["id"])except ValueError:raise HTTPException(400)- res = await database.fetch_one(- """SELECT country_eez."union" FROM power_plant, countries.country_eez WHERE+ res = (+ await database.execute(+ text(+ """SELECT country_eez."union" FROM power_plant, countries.country_eez WHEREST_Contains(ST_Transform(country_eez.geom, 3857), geometry)AND country_eez."union" != 'Antarctica'- AND power_plant.osm_id = :id""",- values={"id": id},- )+ AND power_plant.osm_id = :id"""+ ),+ {"id": id},+ )+ ).fetchone()if not res:raise HTTPException(404)- return RedirectResponse(request.url_for("plant_detail", region=res["union"], id=id))+ return RedirectResponse(request.url_for("plant_detail", region=res._mapping["union"], id=id))@region_required@cache_for(hours=1)-async def plant_detail(request, region):+async def plant_detail(request: Request, region) -> Response:database = request.state["db"]try:plant_id = int(request.path_params["id"])except ValueError:raise HTTPException(404, "Invalid plant ID")- http_client = request.state.http_client+ http_client = request.state["http_client"]plant = await get_plant(database, plant_id, region["gid"])if plant is None: