3
3
import re
4
4
5
5
import ujson
6
- from bottle import Bottle , request , response , static_file
6
+ from bottle import Bottle , HTTPResponse , request , response , static_file
7
7
from sqlalchemy import create_engine
8
- from sqlalchemy .orm import scoped_session , sessionmaker
8
+ from sqlalchemy .orm import sessionmaker
9
9
from sqlalchemy .sql import text
10
10
11
11
from caddy .utils import env
22
22
# https://docs.sqlalchemy.org/en/20/orm/contextual.html#unitofwork-contextual
23
23
database_url = env ("DATABASE_URL" ).replace ("postgis" , "postgresql+psycopg" )
24
24
db_engine = create_engine (database_url )
25
- session = scoped_session ( sessionmaker (bind = db_engine , autoflush = True ))( )
25
+ Session = sessionmaker (bind = db_engine , autoflush = True )
26
26
27
27
# Regex patterns
28
28
LON_LAT_PATTERN = re .compile (r"(?P<lon>-?[0-9]+.[0-9]+),\s*(?P<lat>-?[0-9]+.[0-9]+)" )
@@ -46,10 +46,12 @@ def liveness():
46
46
47
47
@app .route ("/readyz" )
48
48
def readiness ():
49
- result = session . execute ( text ( "SELECT 1" )). fetchone ()
50
-
51
- if result :
49
+ try :
50
+ with Session . begin () as session :
51
+ session . execute ( text ( "SELECT 1" )). fetchone ()
52
52
return "OK"
53
+ except :
54
+ return HTTPResponse (status = 500 , body = "Error" )
53
55
54
56
55
57
@app .route ("/api/<object_id>" )
@@ -66,7 +68,8 @@ def detail(object_id):
66
68
FROM shack_address
67
69
WHERE object_id = :object_id""" )
68
70
sql = sql .bindparams (object_id = object_id )
69
- result = session .execute (sql ).fetchone ()
71
+ with Session .begin () as session :
72
+ result = session .execute (sql ).fetchone ()
70
73
71
74
if result :
72
75
return ujson .dumps (
@@ -107,7 +110,8 @@ def geocode():
107
110
FROM shack_address
108
111
WHERE ST_Intersects(boundary, ST_GeomFromEWKT(:ewkt))""" )
109
112
sql = sql .bindparams (ewkt = ewkt )
110
- result = session .execute (sql ).fetchone ()
113
+ with Session .begin () as session :
114
+ result = session .execute (sql ).fetchone ()
111
115
112
116
# Serialise and return any query result.
113
117
response .content_type = "application/json"
@@ -150,7 +154,8 @@ def geocode():
150
154
WHERE tsv @@ to_tsquery(:tsquery)
151
155
LIMIT :limit""" )
152
156
sql = sql .bindparams (tsquery = tsquery , limit = limit )
153
- result = session .execute (sql ).fetchall ()
157
+ with Session .begin () as session :
158
+ result = session .execute (sql ).fetchall ()
154
159
155
160
# Serialise and return any query results.
156
161
response .content_type = "application/json"
0 commit comments