Skip to content

Open Infrastructure Map, a view of infrastructure data in OpenStreetMap

Hopefully fix db session issue

Russ Garrett366b333ddbc6
diff --git a/web-backend/pyproject.toml b/web-backend/pyproject.toml
index 63bdb4e..661b257 100644
--- a/web-backend/pyproject.toml
+++ b/web-backend/pyproject.toml
@@ -20,6 +20,7 @@ dependencies = [
"sqlalchemy[asyncio]>=2.0.50",
"pydantic>=2.13.4",
"geojson>=3.3.0",
+ "asgiref>=3.11.1",
]
[tool.ruff]
diff --git a/web-backend/src/__init__.py b/web-backend/src/__init__.py
index ea55ead..f97c55e 100644
--- a/web-backend/src/__init__.py
+++ b/web-backend/src/__init__.py
@@ -1,13 +1,17 @@
-from typing import TypedDict
+from typing import TypedDict, cast
import httpx
-from sqlalchemy.ext.asyncio import AsyncConnection
+from sqlalchemy.ext.asyncio import AsyncConnection, AsyncEngine
from starlette.requests import Request as StarletteRequest
class State(TypedDict):
http_client: httpx.AsyncClient
- db: AsyncConnection
+ db_engine: AsyncEngine
Request = StarletteRequest[State]
+
+
+def get_db(request: Request) -> AsyncConnection:
+ return cast(AsyncConnection, request.scope.get("db_connection"))
diff --git a/web-backend/src/main.py b/web-backend/src/main.py
index 4190318..b40c545 100644
--- a/web-backend/src/main.py
+++ b/web-backend/src/main.py
@@ -1,8 +1,14 @@
import contextlib
-from typing import AsyncGenerator
+from typing import AsyncGenerator, cast
import httpx
-from sqlalchemy.ext.asyncio import create_async_engine
+from asgiref.typing import (
+ ASGI3Application,
+ ASGIReceiveCallable,
+ ASGISendCallable,
+ Scope,
+)
+from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
@@ -22,9 +28,26 @@ async def lifespan(app: Starlette) -> AsyncGenerator[State]:
httpx.AsyncClient(
headers={"User-Agent": "Open Infrastructure Map backend (https://openinframap.org)"}
) as client,
- db_engine.connect() as db,
):
- yield {"http_client": client, "db": db}
+ yield {"http_client": client, "db_engine": db_engine}
+
+
+class DBSessionMiddleware:
+ def __init__(self, app: ASGI3Application) -> None:
+ self.app = app
+
+ async def __call__(self, scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None:
+ db = scope.get("state", {}).get("db_engine")
+ if scope["type"] != "http" or db is None:
+ await self.app(scope, receive, send)
+ return
+
+ db = cast(AsyncEngine, db)
+ async with db.connect() as connection:
+ scope["db_connection"] = connection # type: ignore
+ await self.app(scope, receive, send)
+ if connection.in_transaction():
+ await connection.rollback()
app = Starlette(
@@ -37,5 +60,6 @@ app = Starlette(
+ routes,
middleware=[
Middleware(CORSMiddleware, allow_origin_regex="http://localhost.*"),
+ Middleware(DBSessionMiddleware),
],
)
diff --git a/web-backend/src/util.py b/web-backend/src/util.py
index 010fd7f..774d0f9 100644
--- a/web-backend/src/util.py
+++ b/web-backend/src/util.py
@@ -6,7 +6,7 @@ from urllib.parse import unquote_plus
from sqlalchemy import text
from starlette.exceptions import HTTPException
-from . import Request
+from . import Request, get_db
from .config import DEBUG
@@ -14,7 +14,7 @@ def region_required(func):
@wraps(func)
async def wrap_region(request: Request):
region = unquote_plus(request.path_params["region"])
- database = request.state["db"]
+ database = get_db(request)
res = (
await database.execute(
diff --git a/web-backend/src/views/api.py b/web-backend/src/views/api.py
index aa0d9ea..c9a59ba 100644
--- a/web-backend/src/views/api.py
+++ b/web-backend/src/views/api.py
@@ -6,7 +6,7 @@ from starlette.exceptions import HTTPException
from starlette.responses import Response
from starlette.routing import Route
-from .. import Request
+from .. import Request, get_db
from ..util import cache_for
@@ -25,7 +25,7 @@ class SubstationResponse(BaseModel):
@cache_for(600)
async def substation(request: Request) -> Response:
- database = request.state["db"]
+ database = get_db(request)
substation_id = request.path_params["substation_id"]
res = await database.execute(
text(
@@ -69,7 +69,7 @@ class CircuitResponse(BaseModel):
@cache_for(600)
async def circuit(request: Request) -> Response:
- database = request.state["db"]
+ database = get_db(request)
circuit_id = request.path_params["circuit_id"]
res = (
await database.execute(
@@ -105,13 +105,56 @@ async def circuit(request: Request) -> Response:
voltage=res._mapping["voltage"] / 1000 if res._mapping["voltage"] else None,
frequency=res._mapping["frequency"],
geometry=res._mapping["geojson"],
- length=round(res._mapping["length"] or 0 / 1000, 2),
+ length=round((res._mapping["length"] or 0) / 1000, 2),
).model_dump_json(),
media_type="application/json",
)
+class LineResponse(BaseModel):
+ circuits: list[Circuit]
+
+
+@cache_for(600)
+async def line(request: Request) -> Response:
+ database = get_db(request)
+ line_id = request.path_params["line_id"]
+
+ res = await database.execute(
+ text(
+ """
+ SELECT relation.osm_id AS relation_id,
+ relation.tags->'name' AS name,
+ relation.tags->'name:en' AS name_en,
+ relation.tags -> 'frequency' AS frequency,
+ convert_voltage(relation.tags -> 'voltage') AS voltage,
+ member.role
+ FROM osm_power_circuit_relation_member member,
+ osm_power_circuit_relation relation
+ WHERE member = :line_id
+ AND member.osm_id = relation.osm_id
+ """
+ ),
+ {"line_id": int(line_id)},
+ )
+
+ circuits = [
+ Circuit(
+ id=r._mapping["relation_id"],
+ name=r._mapping["name"],
+ name_en=r._mapping["name_en"],
+ voltage=r._mapping["voltage"] / 1000 if r._mapping["voltage"] else None,
+ frequency=r._mapping["frequency"],
+ role=r._mapping["role"],
+ )
+ for r in res
+ ]
+
+ return Response(LineResponse(circuits=circuits).model_dump_json(), media_type="application/json")
+
+
routes = [
Route("/api/substation/{substation_id}", endpoint=substation),
Route("/api/circuit/{circuit_id}", endpoint=circuit),
+ Route("/api/line/{line_id}", endpoint=line),
]
diff --git a/web-backend/src/views/area.py b/web-backend/src/views/area.py
index 02850da..2b37229 100644
--- a/web-backend/src/views/area.py
+++ b/web-backend/src/views/area.py
@@ -9,7 +9,7 @@ from starlette.exceptions import HTTPException
from starlette.responses import RedirectResponse, Response
from starlette.routing import Route
-from .. import Request, charts
+from .. import Request, charts, get_db
from ..data import (
get_commons_thumbnail,
get_plant,
@@ -27,7 +27,7 @@ from ..util import cache_for, region_required
@region_required
@cache_for(hours=1)
async def region(request: Request, region):
- database = request.state["db"]
+ database = get_db(request)
stats_date = await latest_stats_date(database)
async with asyncio.TaskGroup() as tg:
plants = tg.create_task(plant_stats(database, region["gid"], date=stats_date))
@@ -60,7 +60,7 @@ async def region(request: Request, region):
@region_required
@cache_for(hours=1)
async def plants_region(request: Request, region):
- database = request.state["db"]
+ database = get_db(request)
gid = region["gid"]
plants = (
@@ -116,7 +116,7 @@ async def plants_region(request: Request, region):
@region_required
@cache_for(hours=1)
async def plants_construction_region(request: Request, region) -> Response:
- database = request.state["db"]
+ database = get_db(request)
gid = region["gid"]
plants = await database.execute(
@@ -150,7 +150,7 @@ async def plants_construction_region(request: Request, region) -> Response:
@cache_for(hours=1)
async def stats_object(request: Request) -> Response:
- database = request.state["db"]
+ database = get_db(request)
try:
id = int(request.path_params["id"])
except ValueError:
@@ -177,7 +177,7 @@ async def stats_object(request: Request) -> Response:
@region_required
@cache_for(hours=1)
async def plant_detail(request: Request, region) -> Response:
- database = request.state["db"]
+ database = get_db(request)
try:
plant_id = int(request.path_params["id"])
except ValueError:
diff --git a/web-backend/src/views/base.py b/web-backend/src/views/base.py
index e5be142..df5e972 100644
--- a/web-backend/src/views/base.py
+++ b/web-backend/src/views/base.py
@@ -7,7 +7,7 @@ from bokeh.embed import json_item
from starlette.responses import PlainTextResponse, RedirectResponse, Response
from starlette.routing import Route
-from .. import Request, charts
+from .. import Request, charts, get_db
from ..data import (
get_countries,
stats_power_line,
@@ -38,8 +38,8 @@ async def copyright(request: Request) -> Response:
@cache_for(86400)
async def stats(request: Request) -> Response:
+ db = get_db(request)
async with asyncio.TaskGroup() as tg:
- db = request.state["db"]
power_lines = tg.create_task(stats_power_line(db))
countries = tg.create_task(get_countries(db))
return render_template(
@@ -55,7 +55,7 @@ async def stats(request: Request) -> Response:
@cache_for(86400)
async def stats_charts(request: Request) -> Response:
- db = request.state["db"]
+ db = get_db(request)
async with asyncio.TaskGroup() as tg:
lines_plot = tg.create_task(charts.line_length(db))
plants_plot = tg.create_task(charts.plant_count(db))
diff --git a/web-backend/src/views/country.py b/web-backend/src/views/country.py
index c8ee57b..37fd25d 100644
--- a/web-backend/src/views/country.py
+++ b/web-backend/src/views/country.py
@@ -6,7 +6,7 @@ from starlette.exceptions import HTTPException
from starlette.responses import JSONResponse, RedirectResponse, Response
from starlette.routing import Route
-from .. import Request
+from .. import Request, get_db
from ..data import latest_stats_date, plant_source_stats, plant_stats, stats_power_line
from ..templates import render_template
from ..util import cache_for
@@ -23,7 +23,7 @@ def json_area_stats(lines: dict, plants, sources) -> dict:
@cache_for(hours=1)
async def country_json(request: Request) -> Response:
- database = request.state["db"]
+ database = get_db(request)
iso2 = request.path_params["iso2"]
if iso2.upper() != iso2:
return RedirectResponse(request.url.replace(path=f"/stats/country/{iso2.upper()}.json"))
@@ -45,7 +45,7 @@ async def country_json(request: Request) -> Response:
@cache_for(hours=1)
async def country(request: Request) -> Response:
- database = request.state["db"]
+ database = get_db(request)
iso2 = request.path_params["iso2"]
if iso2.upper() != iso2:
return RedirectResponse(request.url.replace(path=f"/stats/country/{iso2.upper()}"))
diff --git a/web-backend/src/views/search.py b/web-backend/src/views/search.py
index 2bacd5d..47cb35e 100644
--- a/web-backend/src/views/search.py
+++ b/web-backend/src/views/search.py
@@ -10,7 +10,7 @@ from starlette.exceptions import HTTPException
from starlette.responses import JSONResponse, Response
from starlette.routing import Route
-from .. import Request
+from .. import Request, get_db
from ..util import cache_for
# Ensure the `create_indexes` script is run after changing this list.
@@ -133,7 +133,7 @@ def sort_key(row: dict) -> int:
@cache_for(86400)
async def search(request: Request) -> Response:
- database = request.state["db"]
+ database = get_db(request)
query = request.query_params.get("q")
language = request.query_params.get("lang", "en")
if language not in SEARCH_LANGUAGES:
diff --git a/web-backend/uv.lock b/web-backend/uv.lock
index d5ebf9b..5eaa209 100644
--- a/web-backend/uv.lock
+++ b/web-backend/uv.lock
@@ -46,6 +46,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/55/1c/d2ec9fbd7d4ed7ec3e72a763c0b9944d9d6f70454234048c00c895c43540/asgi_sitemaps-1.0.0-py3-none-any.whl", hash = "sha256:9040d1a17abd72d800e2f9e567d7d7bdac0fe63858db4608c98bc4c39a895470", size = 9260, upload-time = "2022-02-13T14:23:05.531Z" },
]
+[[package]]
+name = "asgiref"
+version = "3.11.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/63/40/f03da1264ae8f7cfdbf9146542e5e7e8100a4c66ab48e791df9a03d3f6c0/asgiref-3.11.1.tar.gz", hash = "sha256:5f184dc43b7e763efe848065441eac62229c9f7b0475f41f80e207a114eda4ce", size = 38550, upload-time = "2026-02-03T13:30:14.33Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/5c/0a/a72d10ed65068e115044937873362e6e32fab1b7dce0046aeb224682c989/asgiref-3.11.1-py3-none-any.whl", hash = "sha256:e8667a091e69529631969fd45dc268fa79b99c92c5fcdda727757e52146ec133", size = 24345, upload-time = "2026-02-03T13:30:13.039Z" },
+]
+
[[package]]
name = "ast-serialize"
version = "0.5.0"
@@ -519,6 +528,7 @@ source = { virtual = "." }
dependencies = [
{ name = "aiofiles" },
{ name = "asgi-sitemaps" },
+ { name = "asgiref" },
{ name = "async-lru" },
{ name = "asyncpg" },
{ name = "bokeh" },
@@ -550,6 +560,7 @@ dev = [
requires-dist = [
{ name = "aiofiles" },
{ name = "asgi-sitemaps" },
+ { name = "asgiref", specifier = ">=3.11.1" },
{ name = "async-lru" },
{ name = "asyncpg" },
{ name = "bokeh", specifier = "==3.9.1" },