-
Notifications
You must be signed in to change notification settings - Fork 2
/
geocoder.py
195 lines (164 loc) · 6.47 KB
/
geocoder.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
#!/usr/bin/python
import os
import re
import orjson
from bottle import Bottle, HTTPResponse, request, response, static_file
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import text
from caddy.utils import env
dot_env = os.path.join(os.getcwd(), ".env")
if os.path.exists(dot_env):
from dotenv import load_dotenv
load_dotenv()
app = application = Bottle()
# Database connection - create a DB engine and a scoped session for queries.
# https://docs.sqlalchemy.org/en/20/orm/contextual.html#unitofwork-contextual
database_url = env("DATABASE_URL").replace("postgis", "postgresql+psycopg")
db_engine = create_engine(database_url)
Session = sessionmaker(bind=db_engine, autoflush=True)
# Regex patterns
LON_LAT_PATTERN = re.compile(r"(?P<lon>-?[0-9]+.[0-9]+),\s*(?P<lat>-?[0-9]+.[0-9]+)")
ALPHANUM_PATTERN = re.compile(r"[^A-Za-z0-9\s]+")
@app.route("/")
def index():
return static_file("index.html", root="caddy/templates")
@app.route("/favicon.ico")
def favicon():
return static_file("favicon.ico", root="caddy/static")
@app.route("/livez")
def liveness():
return "OK"
@app.route("/readyz")
def readiness():
try:
with Session.begin() as session:
session.execute(text("SELECT 1")).fetchone()
return "OK"
except:
return HTTPResponse(status=500, body="Error")
@app.route("/api/<object_id>")
def detail(object_id):
"""This route will return details of a single land parcel, serialised as a JSON object."""
# Validate `object_id`: this value needs be castable as an integer, even though we handle it as a string.
try:
int(object_id)
except ValueError:
response.status = 400
return "Bad request"
response.content_type = "application/json"
sql = text("""SELECT object_id, address_nice, owner, ST_AsText(centroid), ST_AsText(envelope), ST_AsText(boundary), data
FROM shack_address
WHERE object_id = :object_id""")
sql = sql.bindparams(object_id=object_id)
with Session.begin() as session:
result = session.execute(sql).fetchone()
if result:
return orjson.dumps(
{
"object_id": result[0],
"address": result[1],
"owner": result[2],
"centroid": result[3],
"envelope": result[4],
"boundary": result[5],
"data": result[6],
}
)
else:
return "{}"
@app.route("/api/geocode")
def geocode():
"""This route will accept a query parameter (`q` or `point`), and query for matching land parcels.
`point` must be a string that parses as <float>,<float> and will be used to query for intersection with the `boundary`
spatial column.
`q` will be parsed as free text (non-alphanumeric characters will be ignored) and will be used to perform a text search
against the `tsv` column.
Query results will be returned as serialised JSON objects.
An optional `limit` parameter may be passed in to limit the maximum number of results returned, otherwise the route
defaults to a maximum of five results (no sorting is carried out, so these are simply the first five results from the
query.
"""
q = request.query.q or ""
point = request.query.point or ""
if not q and not point:
response.status = 400
return "Bad request"
# Point intersection query
if point: # Must be in the format lon,lat
m = LON_LAT_PATTERN.match(point)
if m:
lon, lat = m.groups()
# Validate `lon` and `lat` by casting them to float values.
try:
lon, lat = float(lon), float(lat)
except ValueError:
response.status = 400
return "Bad request"
ewkt = f"SRID=4326;POINT({lon} {lat})"
sql = text("""SELECT object_id, address_nice, owner, ST_AsText(centroid), ST_AsText(envelope), ST_AsText(boundary), data
FROM shack_address
WHERE ST_Intersects(boundary, ST_GeomFromEWKT(:ewkt))""")
sql = sql.bindparams(ewkt=ewkt)
with Session.begin() as session:
result = session.execute(sql).fetchone()
# Serialise and return any query result.
response.content_type = "application/json"
if result:
return orjson.dumps(
{
"object_id": result[0],
"address": result[1],
"owner": result[2],
"centroid": result[3],
"envelope": result[4],
"boundary": result[5],
"data": result[6],
}
)
else:
return "{}"
else:
response.status = 400
return "Bad request"
# Address query
# Sanitise the input query: remove any non-alphanumeric/whitespace characters.
q = re.sub(ALPHANUM_PATTERN, "", q)
words = q.split() # Split words on whitespace.
tsquery = "&".join(words)
# Default to return a maximum of five results, allow override via `limit`.
if request.query.limit:
try:
limit = int(request.query.limit)
except ValueError:
response.status = 400
return "Bad request"
else:
limit = 5
sql = text("""SELECT object_id, address_nice, owner, ST_X(centroid), ST_Y(centroid)
FROM shack_address
WHERE tsv @@ to_tsquery(:tsquery)
LIMIT :limit""")
sql = sql.bindparams(tsquery=tsquery, limit=limit)
with Session.begin() as session:
result = session.execute(sql).fetchall()
# Serialise and return any query results.
response.content_type = "application/json"
if result:
j = []
for i in result:
j.append(
{
"object_id": i[0],
"address": i[1],
"owner": i[2],
"lon": i[3],
"lat": i[4],
}
)
return orjson.dumps(j)
else:
return "[]"
if __name__ == "__main__":
from bottle import run
run(application, host="0.0.0.0", port=env("PORT", 8080))