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."""
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