Open Infrastructure Map, a view of infrastructure data in OpenStreetMap
Use a single httpx client for better connection pooling
Russ Garrettac35ffa860bc
diff --git a/web-backend/data.py b/web-backend/data.pyindex 6eb6e5f..5425343 100644--- a/web-backend/data.py+++ b/web-backend/data.py@@ -114,37 +114,38 @@ async def stats_power_line(country=None):@alru_cache(maxsize=1000)-async def get_wikidata(wikidata_id):+async def get_wikidata(wikidata_id: str, client: httpx.AsyncClient) -> dict:wikidata_id = wikidata_id.upper()if not re.match(r"^Q[0-9]+$", wikidata_id):return None- async with httpx.AsyncClient() as client:- resp = await client.get(- f"https://www.wikidata.org/wiki/Special:EntityData/{wikidata_id}.json",- follow_redirects=True,- )- if resp.status_code != 200:- logger.error("Error while fetching wikidata: %s", resp.text)- raise HTTPException(503, "Error while fetching wikidata")- data = resp.json()+ resp = await client.get(+ f"https://www.wikidata.org/wiki/Special:EntityData/{wikidata_id}.json",+ follow_redirects=True,+ )+ if resp.status_code != 200:+ logger.error("Error while fetching wikidata: %s", resp.text)+ raise HTTPException(503, "Error while fetching wikidata")+ data = resp.json()- # ID may have changed if it redirects to another. Fetch the first- # (hopefully only) ID in the list.- wikidata_id = list(data["entities"].keys())[0]- return data["entities"][wikidata_id]+ # ID may have changed if it redirects to another. Fetch the first+ # (hopefully only) ID in the list.+ wikidata_id = list(data["entities"].keys())[0]+ return data["entities"][wikidata_id]@alru_cache(maxsize=1000)-async def get_commons_thumbnail(filename, width=300):+async def get_commons_thumbnail(+ filename: str, client: httpx.AsyncClient, width: int = 300+) -> list:url = ("https://commons.wikimedia.org/w/api.php?"f"action=query&titles=Image:{filename}&prop=imageinfo"f"&iiprop=url&iiurlwidth={width}&format=json")- async with httpx.AsyncClient() as client:- resp = await client.get(url, follow_redirects=True)- if resp.status_code != 200:- raise HTTPException(503, "Error while fetching wikimedia commons image")- data = resp.json()- return list(data["query"]["pages"].values())[0]++ resp = await client.get(url, follow_redirects=True)+ if resp.status_code != 200:+ raise HTTPException(503, "Error while fetching wikimedia commons image")+ data = resp.json()+ return list(data["query"]["pages"].values())[0]diff --git a/web-backend/main.py b/web-backend/main.pyindex 9d7f768..ec8a3d5 100644--- a/web-backend/main.py+++ b/web-backend/main.py@@ -1,3 +1,6 @@+import contextlib+from typing import AsyncIterator, TypedDict+import httpxfrom starlette.responses import PlainTextResponse, RedirectResponsefrom starlette.applications import Starlettefrom starlette.templating import Jinja2Templates@@ -37,10 +40,25 @@ templates.env.filters["country_name"] = country_nametemplates.env.globals["osm_link"] = osm_link+class State(TypedDict):+ http_client: httpx.AsyncClient+++async def lifespan(app: Starlette) -> AsyncIterator[State]:+ await database.connect()+ async with httpx.AsyncClient(+ headers={+ "User-Agent": "Open Infrastructure Map backend (https://openinframap.org)"+ }+ ) as client:+ yield {"http_client": client}+ await database.disconnect()++app = Starlette(debug=DEBUG,- on_startup=[database.connect],- on_shutdown=[database.disconnect],+ lifespan=lifespan,routes=[Mount("/static", app=StaticFiles(directory="static"), name="static"),Route("/sitemap.xml", sitemap),@@ -246,6 +264,8 @@ async def plant_detail(request, country):except ValueError:raise HTTPException(404, "Invalid plant ID")+ http_client = request.state.http_client+plant = await get_plant(plant_id, country["gid"])if plant is None:raise HTTPException(404, "Nonexistent power plant")@@ -253,7 +273,7 @@ async def plant_detail(request, country):generator_summary = await get_plant_generator_summary(plant_id)if "wikidata" in plant["tags"]:- wd = await get_wikidata(plant["tags"]["wikidata"])+ wd = await get_wikidata(plant["tags"]["wikidata"], http_client)else:wd = None@@ -264,7 +284,7 @@ async def plant_detail(request, country):and wd["claims"]["P18"][0]["mainsnak"]["datatype"] == "commonsMedia"):image_data = await get_commons_thumbnail(- wd["claims"]["P18"][0]["mainsnak"]["datavalue"]["value"], 400+ wd["claims"]["P18"][0]["mainsnak"]["datavalue"]["value"], http_client, 400)ref_tags = []diff --git a/web-backend/test_data.py b/web-backend/test_data.pyindex d7fefa5..e928475 100644--- a/web-backend/test_data.py+++ b/web-backend/test_data.py@@ -1,15 +1,20 @@import pytest+import httpxfrom data import get_wikidata, get_commons_thumbnail@pytest.mark.asyncioasync def test_get_wikidata():- result = await get_wikidata("Q42")- assert result is not None- assert "claims" in result+ async with httpx.AsyncClient() as client:+ result = await get_wikidata("Q42", client)+ assert result is not None+ assert "claims" in result@pytest.mark.asyncioasync def test_get_commons_thumbnail():- thumbnail = await get_commons_thumbnail("File:Albert Einstein Head.jpg", 400)- assert thumbnail is not None+ async with httpx.AsyncClient() as client:+ thumbnail = await get_commons_thumbnail(+ "File:Albert Einstein Head.jpg", client, 400+ )+ assert thumbnail is not Nonediff --git a/web-backend/wikidata.py b/web-backend/wikidata.pyindex 97a15d8..b536d35 100644--- a/web-backend/wikidata.py+++ b/web-backend/wikidata.py@@ -11,9 +11,10 @@ from main import app@cache_for(86400)async def wikidata(request):wikidata_id = request.path_params["wikidata_id"].upper()+ http_client = request.state.http_clientresponse = {}- data = await get_wikidata(wikidata_id)+ data = await get_wikidata(wikidata_id, http_client)if data is None:raise HTTPException(404, "Wikidata item not found")@@ -24,7 +25,7 @@ async def wikidata(request):):response["image"] = data["claims"]["P18"][0]["mainsnak"]["datavalue"]["value"]image_data = await get_commons_thumbnail(- data["claims"]["P18"][0]["mainsnak"]["datavalue"]["value"]+ data["claims"]["P18"][0]["mainsnak"]["datavalue"]["value"], http_client)response["thumbnail"] = image_data["imageinfo"][0]["thumburl"]