Skip to content

Commit d7f6225

Browse files
committed
Fetch all stop data at once in stop registry importer
1 parent 83b6e96 commit d7f6225

File tree

1 file changed

+77
-49
lines changed

1 file changed

+77
-49
lines changed

stop-registry-importer/importer.py

+77-49
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
#!/usr/bin/env python3
22

3+
import datetime
34
import pymssql
45
import requests
56
import simplejson as json
67
import environ
7-
import os
88

99
env = environ.Env(
1010
GRAPHQL_URL=(str,'http://localhost:3201/v1/graphql'),
@@ -25,9 +25,9 @@
2525
jore3DatabaseUrl = env('JORE3_DATABASE_URL')
2626
jore3DatabaseName = env('JORE3_DATABASE_NAME')
2727

28-
# Replace these to use different target
28+
def get_jore3_stops():
2929

30-
def get_jore3_stops_for_area(pysakki_alue):
30+
stopPlaces = []
3131
with pymssql.connect(jore3DatabaseUrl, jore3Username, jore3Password, jore3DatabaseName) as conn:
3232

3333
with conn.cursor(as_dict=True) as cursor:
@@ -37,11 +37,18 @@ def get_jore3_stops_for_area(pysakki_alue):
3737
inner join jr_lij_pysakkialue pa on (p.pysalueid = pa.pysalueid)
3838
inner join jr_esteettomyys e on (p.soltunnus = e.tunnus)
3939
inner join jr_varustelutiedot_uusi vt on (p.soltunnus = vt.tunnus)
40-
where p.pysalueid = %s
41-
order by p.pysviimpvm asc;""", params=pysakki_alue)
40+
order by p.pysviimpvm asc;""")
4241

43-
for row in cursor:
44-
yield row
42+
stopPlaces = cursor.fetchall()
43+
44+
print(f"Found {len(stopPlaces)} stop places")
45+
46+
stopPlacesByArea = {}
47+
48+
for x in stopPlaces:
49+
stopPlacesByArea.setdefault(x['pysalueid'], []).append(x)
50+
51+
return stopPlacesByArea
4552

4653
def get_jore3_stop_areas():
4754
with pymssql.connect(jore3DatabaseUrl, jore3Username, jore3Password, jore3DatabaseName) as conn:
@@ -76,7 +83,6 @@ def get_stop_points():
7683
headers = {'content-type': 'application/json; charset=UTF-8',
7784
'x-hasura-admin-secret': secret}
7885
response = requests.post(graphql, headers=headers, json={"query": query})
79-
print(response)
8086
json_data = response.json()
8187
if not json_data['data']:
8288
return {}
@@ -112,8 +118,11 @@ def update_stop_point(label, netexid):
112118
headers = {'content-type': 'application/json; charset=UTF-8',
113119
'x-hasura-admin-secret': secret}
114120
response = requests.post(graphql, headers=headers, json={"query": mutation, "variables": variables})
115-
print(response.content)
116-
121+
formatted = response.json()
122+
if formatted['data']:
123+
print(f"Scheduled stop point {label} reference updated")
124+
else:
125+
print(f"Scheduled stop point {label} reference update failed")
117126

118127
def mapStopModel(jore3model):
119128
match jore3model:
@@ -337,58 +346,77 @@ def update_stop_place(lat, lon, validityStart, validityEnd, jore3result, quayInp
337346
'x-hasura-admin-secret': secret}
338347
response = requests.post(graphql, headers=headers, json={"query": stopMutation2, "variables": variables2})
339348

340-
print(response)
341-
print(response.content)
349+
formatted = response.json()
342350

343-
if (json.loads(response.content)['data']):
344-
return json.loads(response.content)['data']['stop_registry']['mutateStopPlace'][0]['quays']
351+
if formatted['data']:
352+
return formatted['data']['stop_registry']['mutateStopPlace'][0]['quays']
353+
if formatted['errors']:
354+
if formatted['errors'][0]['message']:
355+
print(formatted['errors'][0]['message'])
356+
else:
357+
print(f"Stop place {jore3result['pysalueid']} update failed!")
345358

346359
return {}
347360

361+
startTime = datetime.datetime.now()
362+
348363
stopPoints = get_stop_points()
349364
print(f"Found {len(stopPoints)} stop points")
350365
added = 0
351366

367+
stopPlaces = get_jore3_stops()
368+
index = 0
369+
352370
for stopArea in get_jore3_stop_areas():
371+
index += 1
372+
print(f"Handling stop area {index}")
353373
quayInput = []
354374
latCoords = []
355375
lonCoords = []
356376
validityStarts = []
357377
validityEnds = []
358378
lastStop = None
359-
for stop in get_jore3_stops_for_area(stopArea['pysalueid']):
360-
try:
361-
stopLabel = stop['solkirjain'] + stop['sollistunnus']
362-
if not stopLabel in stopPoints:
363-
continue
364-
stopPoint = stopPoints[stopLabel][0]
365-
lat = stopPoint['lat']
366-
lon = stopPoint['lon']
367-
validityStart = stopPoint['validity_start']
368-
validityEnd = stopPoint['validity_end']
369-
quayInput.append(quayInputForJore3Stop(stop, stopPoint['label'], validityStart, validityEnd , lon, lat))
370-
latCoords.append(lat)
371-
lonCoords.append(lon)
372-
validityStarts.append(validityStart)
373-
validityEnds.append(validityEnd)
374-
lastStop = stop
375-
except:
376-
print(f"Failed to handle stop {stop}")
377-
if (len(lonCoords) > 0 and len(latCoords) > 0 and len(validityStarts) > 0 and len(validityEnds) > 0):
378-
379-
# Average coordinates of quays for the stop place
380-
stopPlaceLon = sum(lonCoords) / len(lonCoords)
381-
stopPlaceLat = sum(latCoords) / len(latCoords)
382-
383-
# Use min / max validity period of the stop points for the stop place
384-
stopPlaceValidityStart = min(validityStarts)
385-
stopPlaceValidityEnd = max(validityEnds)
386-
387-
netexIds = update_stop_place(stopPlaceLat, stopPlaceLon, stopPlaceValidityStart, stopPlaceValidityEnd, lastStop, quayInput)
388-
if (netexIds):
389-
added += 1
390-
for netexAssociation in netexIds:
391-
update_stop_point(netexAssociation['publicCode'], netexAssociation['id'])
392-
393-
379+
try:
380+
for stop in stopPlaces[stopArea['pysalueid']]:
381+
try:
382+
stopLabel = stop['solkirjain'] + stop['sollistunnus']
383+
if not stopLabel in stopPoints:
384+
continue
385+
stopPoint = stopPoints[stopLabel][0]
386+
lat = stopPoint['lat']
387+
lon = stopPoint['lon']
388+
validityStart = stopPoint['validity_start']
389+
validityEnd = stopPoint['validity_end']
390+
quayInput.append(quayInputForJore3Stop(stop, stopPoint['label'], validityStart, validityEnd , lon, lat))
391+
latCoords.append(lat)
392+
lonCoords.append(lon)
393+
validityStarts.append(validityStart)
394+
validityEnds.append(validityEnd)
395+
lastStop = stop
396+
except:
397+
print(f"Failed to handle stop {stop['soltunnus']}: {stop['pysnimi']}")
398+
if (len(lonCoords) > 0 and len(latCoords) > 0 and len(validityStarts) > 0 and len(validityEnds) > 0):
399+
400+
# Average coordinates of quays for the stop place
401+
stopPlaceLon = sum(lonCoords) / len(lonCoords)
402+
stopPlaceLat = sum(latCoords) / len(latCoords)
403+
404+
# Use min / max validity period of the stop points for the stop place
405+
stopPlaceValidityStart = min(validityStarts)
406+
stopPlaceValidityEnd = max(validityEnds)
407+
408+
netexIds = update_stop_place(stopPlaceLat, stopPlaceLon, stopPlaceValidityStart, stopPlaceValidityEnd, lastStop, quayInput)
409+
if (netexIds):
410+
added += 1
411+
for netexAssociation in netexIds:
412+
update_stop_point(netexAssociation['publicCode'], netexAssociation['id'])
413+
414+
except Exception as e:
415+
print(f"Failed to handle stop area {stopArea['pysalueid']}")
416+
print(e)
417+
418+
endTime = datetime.datetime.now()
419+
duration = endTime - startTime
394420
print(f"Added {added} stop places")
421+
minutes = duration.seconds // 60
422+
print(f"Import took {minutes} minutes {duration.seconds - (minutes * 60)} seconds")

0 commit comments

Comments
 (0)