Replace psycopg2 use with sqlalchemy

Closes: #19
This commit is contained in:
Edward Betts 2023-12-27 10:38:35 +00:00
parent a8c4cc51f6
commit 9112c685c4

View file

@ -1,16 +1,17 @@
"""Reverse geocode civil parishes in Scotland.""" """Reverse geocode civil parishes in Scotland."""
import psycopg2 from sqlalchemy import func
from flask import current_app
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.""" """Find civil parish in Scotland for given lat/lon."""
conn = psycopg2.connect(**current_app.config["DB_PARAMS"]) point = func.ST_Transform(func.ST_SetSRID(func.ST_MakePoint(lon, lat), 4326), 27700)
cur = conn.cursor() result = (
session.query(Scotland.code)
point = f"ST_Transform(ST_SetSRID(ST_MakePoint({lon}, {lat}), 4326), 27700)" .filter(func.ST_Contains(Scotland.geom, point))
cur.execute(f"select code, name from scotland where st_contains(geom, {point});") .first()
row = cur.fetchone() )
conn.close() return result[0] if result else None
return row[0] if row else None