Skip to content

Commit

Permalink
Cache country shapes
Browse files Browse the repository at this point in the history
  • Loading branch information
Zaczero committed Feb 19, 2024
1 parent b029ebe commit 1a4f392
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion states/country_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 = {}

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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)

Expand Down

0 comments on commit 1a4f392

Please sign in to comment.