-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathingest_data.py
More file actions
78 lines (60 loc) · 2.25 KB
/
ingest_data.py
File metadata and controls
78 lines (60 loc) · 2.25 KB
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
import os
import mysql.connector
from mysql.connector import errorcode
from datetime import datetime
import sys
sys.path.insert(0, 'NextBus/')
from NextBusClient import NextBusClient
user = 'root' #os.environ['MYSQL_USER']
password = 'root' #os.environ['MYSQL_PASSWORD']
db = 'ttc_bus_data'
config = {
'user': user,
'password': password,
'host': 'localhost',
'database': 'ttc_bus_data',
'raise_on_warnings': True,
}
def remove_old_data(db_connection):
query = "DELETE FROM vehicle_locations WHERE updated_at < (NOW() - INTERVAL 1 MINUTE)"
cursor = db_connection.cursor()
cursor.execute(query)
db_connection.commit()
cursor.close()
def ingest_data(db_connection):
next_bus_client = NextBusClient()
add_vehicle_location = ("INSERT INTO vehicle_locations "
"(id, longitude, latitude, route_number, direction, updated_at) "
"VALUES (%(id)s, %(longitude)s, %(latitude)s, %(route_number)s, %(direction)s, %(updated_at)s) "
"ON DUPLICATE KEY UPDATE "
"longitude=VALUES(longitude),latitude=VALUES(latitude),route_number=VALUES(route_number),direction=VALUES(direction), updated_at=VALUES(updated_at)")
cursor = db_connection.cursor()
vehicles = next_bus_client.vehicle_locations('ttc', 0)['vehicle']
for vehicle in vehicles:
vehicle_data = {
'id': vehicle['id'],
'longitude': vehicle['lon'],
'latitude': vehicle['lat'],
'route_number': vehicle['routeTag'],
'direction': vehicle['heading'],
'updated_at': datetime.now()
}
cursor.execute(add_vehicle_location, vehicle_data)
db_connection.commit()
cursor.close()
def main():
try:
db_connection = mysql.connector.connect(**config)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Incorrect username or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
return
# remove_old_data(db_connection)
ingest_data(db_connection)
db_connection.close()
if __name__ == '__main__':
main()