From 1a4f392a2c7826184f7d065cc6c785c75e85aff0 Mon Sep 17 00:00:00 2001 From: Kamil Monicz Date: Mon, 19 Feb 2024 14:48:32 +0100 Subject: [PATCH] Cache country shapes --- states/country_state.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/states/country_state.py b/states/country_state.py index 66494c6..a7fd929 100644 --- a/states/country_state.py +++ b/states/country_state.py @@ -6,6 +6,7 @@ from dacite import from_dict from sentry_sdk import start_transaction, trace from shapely.geometry import Point, mapping, shape +from shapely.geometry.base import BaseGeometry from config import COUNTRY_COLLECTION, COUNTRY_UPDATE_DELAY from models.bbox import BBox @@ -36,6 +37,9 @@ def get_unique(self, tags: dict[str, str]) -> str: return 'XX' +shape_cache: dict[str, BaseGeometry] = {} + + def _get_names(tags: dict[str, str]) -> dict[str, str]: names = {} @@ -107,6 +111,8 @@ async def _update_db() -> None: await COUNTRY_COLLECTION.insert_many(insert_many_arg, session=s) await set_state_doc('country', {'update_timestamp': data_timestamp}, session=s) + shape_cache.clear() + print('🗺️ Updating country codes') from states.aed_state import AEDState @@ -139,7 +145,12 @@ async def get_all_countries(filter: dict | None = None) -> Sequence[Country]: result = [] async for c in cursor: - result.append(from_dict(Country, {**c, 'geometry': shape(c['geometry'])})) # noqa: PERF401 + geometry = shape_cache.get(c['code']) + if geometry is None: + geometry = shape(c['geometry']) + shape_cache[c['code']] = geometry + + result.append(from_dict(Country, {**c, 'geometry': geometry})) return tuple(result)