From 9112c685c4d5f2de17f5f79dbc2239bc4ed11280 Mon Sep 17 00:00:00 2001 From: Edward Betts Date: Wed, 27 Dec 2023 10:38:35 +0000 Subject: [PATCH] Replace psycopg2 use with sqlalchemy Closes: #19 --- geocode/scotland.py | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/geocode/scotland.py b/geocode/scotland.py index 27c50e3..f377c84 100644 --- a/geocode/scotland.py +++ b/geocode/scotland.py @@ -1,16 +1,17 @@ """Reverse geocode civil parishes in Scotland.""" -import psycopg2 -from flask import current_app +from sqlalchemy import func + +from geocode.database import session +from geocode.model import Scotland -def get_scotland_code(lat: str | float, lon: str | float) -> str | None: +def get_scotland_code(lat: float, lon: float) -> str | None: """Find civil parish in Scotland for given lat/lon.""" - conn = psycopg2.connect(**current_app.config["DB_PARAMS"]) - cur = conn.cursor() - - point = f"ST_Transform(ST_SetSRID(ST_MakePoint({lon}, {lat}), 4326), 27700)" - cur.execute(f"select code, name from scotland where st_contains(geom, {point});") - row = cur.fetchone() - conn.close() - return row[0] if row else None + point = func.ST_Transform(func.ST_SetSRID(func.ST_MakePoint(lon, lat), 4326), 27700) + result = ( + session.query(Scotland.code) + .filter(func.ST_Contains(Scotland.geom, point)) + .first() + ) + return result[0] if result else None