Fixes for data requests failing

This commit is contained in:
Lucas
2021-09-27 17:41:15 -04:00
parent f5fab69877
commit 2bb0af5c6b
3 changed files with 52 additions and 62 deletions

View File

@@ -1,7 +1,7 @@
import os import os
import threading import threading
from flask import Flask, jsonify, render_template, request from flask import Flask, jsonify, render_template, request, abort
from mta_manager import MTA from mta_manager import MTA
from pprint import pprint from pprint import pprint
import pandas as pd import pandas as pd
@@ -12,7 +12,6 @@ load_dotenv()
app = Flask(__name__) app = Flask(__name__)
app.secret_key = "SuperSecretDontEvenTryToGuessMeGGEZNoRe" app.secret_key = "SuperSecretDontEvenTryToGuessMeGGEZNoRe"
app.debug = True
app._static_folder = os.path.abspath("templates/static/") app._static_folder = os.path.abspath("templates/static/")
stops = pd.read_csv("stops.txt") stops = pd.read_csv("stops.txt")
@@ -48,12 +47,12 @@ def link_to_station(data):
@app.route("/mta_data", methods=["POST"]) @app.route("/mta_data", methods=["POST"])
def get_mta_data(): def get_mta_data():
station = request.json["station"] station = request.json["station"]
print(jsonify( if station in subway_data:
subway_data[station] return jsonify(
)) subway_data[station]
return jsonify( )
subway_data[station] else:
) abort(404)
@app.route("/stops", methods=["GET"]) @app.route("/stops", methods=["GET"])
@@ -73,6 +72,7 @@ def get_stop_id():
if __name__ == "__main__": if __name__ == "__main__":
api_key = os.getenv('MTA_API_KEY', '') api_key = os.getenv('MTA_API_KEY', '')
mtaController = MTA( mtaController = MTA(
api_key, api_key,
["A", "C", "E", "1", "2", "3"], ["A", "C", "E", "1", "2", "3"],
@@ -83,6 +83,7 @@ if __name__ == "__main__":
async def mta_callback(routes): async def mta_callback(routes):
global subway_data global subway_data
subway_data = link_to_station(mtaController.convert_routes_to_station_first(routes)) subway_data = link_to_station(mtaController.convert_routes_to_station_first(routes))
app.logger.info(f"Updated Subway Data - {subway_data}")
class threadWrapper(threading.Thread): class threadWrapper(threading.Thread):
@@ -105,7 +106,9 @@ if __name__ == "__main__":
for t in threads: for t in threads:
t.start() t.start()
app.run(host="localhost", debug=True, port=5000) debug = os.getenv("DEBUG", 'False').lower() in ('true', '1', 't')
app.run(host="localhost", debug= debug, port=5000)
# Wait for all threads to complete # Wait for all threads to complete
for t in threads: for t in threads:
t.join() t.join()

View File

@@ -1,38 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- <link rel="stylesheet" href="/static/css/style.css">-->
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="/static/js/DataRequests.js"></script>
<meta charset="UTF-8">
<title>SUBWAY DISPLAY!</title>
</head>
<body>
<div id="main_div">
<div id="container">
<span>PI MTA TRACKER</span>
</div>
<div class="station_div">
<div class="station_header">
<span>Times Square Station</span>
</div>
<div class="direction_div">
<div class="direction_header"> North</div>
<div>Train 1 Info</div>
<div>Train 2 Info</div>
<div>Train 3 Info</div>
</div>
<div class="direction_div">
<div class="direction_header"> South</div>
<div>Train 1 Info</div>
<div>Train 2 Info</div>
<div>Train 3 Info</div>
</div>
</div>
<button id="test_button">Test Button</button>
<span id="result"></span>
</div>

View File

@@ -2,22 +2,21 @@ $(document).ready(function () {
const interval = setInterval(function () { const interval = setInterval(function () {
updateData($('#station_1')) updateData($('#station_1'))
updateData($('#station_2'))
}, 5000); }, 5000);
const interval2 = setInterval(function () {
updateData($('#station_2'))
}, 6000);
function updateData(station) { function updateData(station) {
$.ajax({ $.ajax({
type: "POST", type: "POST",
//the url where you want to sent the userName and password to
url: '/mta_data', url: '/mta_data',
contentType: "application/json", contentType: "application/json",
dataType: "json", dataType: "json",
async: true, async: true,
//json object to sent to the authentication url
data: JSON.stringify({"station": station.find('.station-name:first').get(0).innerText}, null, '\t'), data: JSON.stringify({"station": station.find('.station-name:first').get(0).innerText}, null, '\t'),
success: function (data, text) { success: function (data, text) {
// console.log(data)
updateStation(station, data) updateStation(station, data)
}, },
error: function (request, status, error) { error: function (request, status, error) {
@@ -27,32 +26,58 @@ $(document).ready(function () {
} }
function updateStation(station, data) { function updateStation(station, data) {
//get first item
updateDirections(station, data, "North"); updateDirections(station, data, "North");
updateDirections(station, data, "South"); updateDirections(station, data, "South");
} }
function updateDirections(station, data, direction) { function updateDirections(station, data, direction) {
// console.log(direction)
// console.log(".card:".concat(direction === "North" ? "first" : "last"))
n = data[direction] n = data[direction]
// console.log(data[direction])
list_items = station.find(".card:".concat(direction === "North" ? "first" : "last")).find(".station-info") list_items = station.find(".card:".concat(direction === "North" ? "first" : "last")).find(".station-info")
var i = 0; var i = 0;
for (var train in n) { for (var train in n) {
// console.log(train)
// console.log(list_items)
updateLineItem(list_items.get(i), n[train], train) updateLineItem(list_items.get(i), n[train], train)
i = i + 1 i = i + 1
} }
if (i < 3) {
console.log("Only 2 items updated")
for (let remainingIndex = i; remainingIndex < 3; remainingIndex++) {
updateLineItem(list_items.get(i), "No Trains Available", "N/A")
}
}
} }
function updateLineItem(listItem, times, train) { function updateLineItem(listItem, times, train) {
// console.log(times) var timeString;
$(listItem).find("img").attr("src", "/static/images/lines/" + train + ".svg") if (typeof times === 'string' || times instanceof String) {
$(listItem).find("h1").text(times.sort(function (a, b) { timeString = times;
return a - b; } else {
}).join(", ")); timeString = times.sort(function (a, b) {
return a - b;
}).join(", ");
}
$(listItem).find("h1").text(timeString);
if (imageExists("/static/images/lines/" + train + ".svg")) {
$(listItem).show()
$(listItem).find("img").attr("src", "/static/images/lines/" + train + ".svg")
} else if (train === "N/A"){
console.log("Route Is NA - Disabling Route")
console.log($(listItem))
$(listItem).hide()
}
}
function imageExists(image_url) {
var http = new XMLHttpRequest();
http.open('HEAD', image_url, false);
http.send();
return http.status != 404;
} }
}); });