def update_live_locations(): # Delete existing data from vehicles Vehicle.query.delete() # Get live vehicles as json data json_data = requests.get(API_VEHICLES, headers=API_HEADER) vehicle_dict = json.loads(json_data.text) # Array of service objects vehicles = vehicle_dict["vehicles"] # Update the vehicle table's last_updated field vehicles_date = datetime.fromtimestamp(int(vehicle_dict["last_updated"])) update_table_date("vehicle", vehicles_date) # Create a vehicle instance of each vehicle. for vehicle in vehicles: new_vehicle = Vehicle() new_vehicle.vehicle_id = vehicle["vehicle_id"] new_vehicle.destination = vehicle["destination"] new_vehicle.speed = vehicle["speed"] new_vehicle.heading = vehicle["heading"] new_vehicle.latitude = vehicle["latitude"] new_vehicle.longitude = vehicle["longitude"] new_vehicle.service_name = vehicle["service_name"] db_session.add(new_vehicle) db_session.commit() db_session.flush()
def update_services_stops(): # Delete all data first delete_services_stops() # Get services as json data json_data = requests.get(API_SERVICES, headers=API_HEADER) service_dict = json.loads(json_data.text) # Array of service objects services = service_dict["services"] # Get stops as json data json_data = requests.get(API_STOPS, headers=API_HEADER) stop_dict = json.loads(json_data.text) # Array of stop objects stops = stop_dict["stops"] # Update the tables' last_updated field service_date = datetime.fromtimestamp(int(service_dict["last_updated"])) update_table_date("service", service_date) stop_date = datetime.fromtimestamp(int(stop_dict["last_updated"])) update_table_date("stop", stop_date) # Create a service instance of each service and store them in a new dictionary service_dict = {} for service in services: new_service = Service() new_service.name = service["name"] new_service.service_type = service["service_type"] new_service.description = service["description"] new_service.route = json.dumps(service["routes"][0]["points"]) if len(service["routes"]) > 0 else "none" service_dict[service["name"]] = new_service db_session.add(new_service) # Create a stop instance of each stop and add corresponding services to them for stop in stops: new_stop = Stop() new_stop.name = stop["name"] new_stop.latitude = stop["latitude"] new_stop.longitude = stop["longitude"] # Add services to stops # Must take the set because sometimes the services are listed multiple times for a particular stop. stop_services = set(stop["services"]) for service_name in stop_services: new_stop.services.append(service_dict[service_name]) db_session.add(new_stop) db_session.commit() db_session.flush()