Moving code around
This commit is contained in:
parent
fbcf3d102b
commit
54b280655f
4 changed files with 85 additions and 36 deletions
25
geocode/database.py
Normal file
25
geocode/database.py
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
from sqlalchemy import create_engine, func
|
||||
from sqlalchemy.orm import scoped_session, sessionmaker
|
||||
|
||||
session = scoped_session(sessionmaker())
|
||||
|
||||
|
||||
def init_db(db_url):
|
||||
session.configure(bind=get_engine(db_url))
|
||||
|
||||
|
||||
def get_engine(db_url, echo=False):
|
||||
return create_engine(db_url, pool_recycle=3600, echo=echo)
|
||||
|
||||
|
||||
def init_app(app, echo=False):
|
||||
db_url = app.config["DB_URL"]
|
||||
session.configure(bind=get_engine(db_url, echo=echo))
|
||||
|
||||
@app.teardown_appcontext
|
||||
def shutdown_session(exception=None):
|
||||
session.remove()
|
||||
|
||||
|
||||
def now_utc():
|
||||
return func.timezone("utc", func.now())
|
||||
34
geocode/model.py
Normal file
34
geocode/model.py
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.schema import Column
|
||||
from sqlalchemy.types import Integer, Float, Numeric, String
|
||||
from sqlalchemy.dialects import postgresql
|
||||
from geoalchemy2 import Geometry
|
||||
from .database import session
|
||||
|
||||
Base = declarative_base()
|
||||
Base.query = session.query_property()
|
||||
|
||||
class Polygon(Base):
|
||||
__tablename__ = "planet_osm_polygon"
|
||||
|
||||
osm_id = Column(Integer, primary_key=True, autoincrement=False)
|
||||
|
||||
way_area = Column(Float)
|
||||
tags = Column(postgresql.HSTORE)
|
||||
way = Column(Geometry("GEOMETRY", srid=4326, spatial_index=True), nullable=False)
|
||||
|
||||
class Scotland(Base):
|
||||
__tablename__ = "scotland"
|
||||
|
||||
gid = Column(Integer, primary_key=True)
|
||||
shape_leng = Column(Numeric)
|
||||
shape_area = Column(Numeric)
|
||||
code = Column(String(3))
|
||||
c91code1 = Column(String(5))
|
||||
c91code2 = Column(String(5))
|
||||
c91code3 = Column(String(5))
|
||||
c91code4 = Column(String(5))
|
||||
name = Column(String(50))
|
||||
|
||||
geom = Column(Geometry("MULTIPOLYGON", srid=27700))
|
||||
|
||||
12
geocode/scotland.py
Normal file
12
geocode/scotland.py
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
from flask import current_app
|
||||
import psycopg2
|
||||
|
||||
def get_scotland_code(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
|
||||
Loading…
Add table
Add a link
Reference in a new issue