refactor: rename functions across codebase for clarity
All checks were successful
CI / Lint (push) Successful in 7s
CI / Test (push) Successful in 5s
CI / Build & Push (push) Successful in 14s

This commit is contained in:
2026-03-29 10:21:01 -04:00
parent a4dc7dff52
commit dd5ac945bd
7 changed files with 70 additions and 69 deletions

View File

@@ -12,7 +12,7 @@ logger = logging.getLogger(__name__)
EASTERN = ZoneInfo("America/New_York") EASTERN = ZoneInfo("America/New_York")
def get_scoreboard_data(): def fetch_scores():
now = datetime.now(EASTERN) now = datetime.now(EASTERN)
start_time_evening = now.replace(hour=19, minute=0, second=0, microsecond=0) start_time_evening = now.replace(hour=19, minute=0, second=0, microsecond=0)
end_time_morning = now.replace(hour=3, minute=0, second=0, microsecond=0) end_time_morning = now.replace(hour=3, minute=0, second=0, microsecond=0)
@@ -31,8 +31,8 @@ def get_scoreboard_data():
return None return None
def store_scoreboard_data(): def refresh_scores():
scoreboard_data = get_scoreboard_data() scoreboard_data = fetch_scores()
if scoreboard_data: if scoreboard_data:
with open(SCOREBOARD_DATA_FILE, "w") as json_file: with open(SCOREBOARD_DATA_FILE, "w") as json_file:
json.dump(scoreboard_data, json_file) json.dump(scoreboard_data, json_file)

View File

@@ -7,7 +7,7 @@ from app.config import DB_PATH
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def process_record(record): def format_record(record):
if record == "N/A": if record == "N/A":
return "N/A" return "N/A"
else: else:
@@ -16,7 +16,7 @@ def process_record(record):
return "-".join(formatted_parts) return "-".join(formatted_parts)
def extract_game_info(scoreboard_data): def parse_games(scoreboard_data):
if not scoreboard_data: if not scoreboard_data:
return [] return []
@@ -36,8 +36,8 @@ def extract_game_info(scoreboard_data):
"Home Logo": game["homeTeam"]["logo"], "Home Logo": game["homeTeam"]["logo"],
"Away Logo": game["awayTeam"]["logo"], "Away Logo": game["awayTeam"]["logo"],
"Game State": game_state, "Game State": game_state,
"Period": process_period(game), "Period": get_period(game),
"Time Remaining": process_time_remaining(game), "Time Remaining": get_time_remaining(game),
"Time Running": game["clock"]["running"] "Time Running": game["clock"]["running"]
if game_state == "LIVE" if game_state == "LIVE"
else "N/A", else "N/A",
@@ -45,11 +45,11 @@ def extract_game_info(scoreboard_data):
if game_state == "LIVE" if game_state == "LIVE"
else "N/A", else "N/A",
"Priority": calculate_game_priority(game), "Priority": calculate_game_priority(game),
"Start Time": process_start_time(game), "Start Time": get_start_time(game),
"Home Record": process_record(game["homeTeam"]["record"]) "Home Record": format_record(game["homeTeam"]["record"])
if game["gameState"] in ["PRE", "FUT"] if game["gameState"] in ["PRE", "FUT"]
else "N/A", else "N/A",
"Away Record": process_record(game["awayTeam"]["record"]) "Away Record": format_record(game["awayTeam"]["record"])
if game["gameState"] in ["PRE", "FUT"] if game["gameState"] in ["PRE", "FUT"]
else "N/A", else "N/A",
"Home Shots": game["homeTeam"]["sog"] "Home Shots": game["homeTeam"]["sog"]
@@ -77,7 +77,7 @@ def convert_game_state(game_state):
return state_mapping.get(game_state, game_state) return state_mapping.get(game_state, game_state)
def process_period(game): def get_period(game):
if game["gameState"] in ["PRE", "FUT"]: if game["gameState"] in ["PRE", "FUT"]:
return 0 return 0
elif game["gameState"] in ["FINAL", "OFF"]: elif game["gameState"] in ["FINAL", "OFF"]:
@@ -86,7 +86,7 @@ def process_period(game):
return game["periodDescriptor"]["number"] return game["periodDescriptor"]["number"]
def process_time_remaining(game): def get_time_remaining(game):
if game["gameState"] in ["PRE", "FUT"]: if game["gameState"] in ["PRE", "FUT"]:
return "20:00" return "20:00"
elif game["gameState"] in ["FINAL", "OFF"]: elif game["gameState"] in ["FINAL", "OFF"]:
@@ -96,10 +96,10 @@ def process_time_remaining(game):
return "END" if time_remaining == "00:00" else time_remaining return "END" if time_remaining == "00:00" else time_remaining
def process_start_time(game): def get_start_time(game):
if game["gameState"] in ["PRE", "FUT"]: if game["gameState"] in ["PRE", "FUT"]:
utc_time = game["startTimeUTC"] utc_time = game["startTimeUTC"]
est_time = utc_to_est_time(utc_time) est_time = utc_to_eastern(utc_time)
return est_time.lstrip("0") return est_time.lstrip("0")
else: else:
return "N/A" return "N/A"
@@ -224,7 +224,7 @@ def get_team_standings(team_name):
} }
def utc_to_est_time(utc_time): def utc_to_eastern(utc_time):
utc_datetime = datetime.strptime(utc_time, "%Y-%m-%dT%H:%M:%SZ") utc_datetime = datetime.strptime(utc_time, "%Y-%m-%dT%H:%M:%SZ")
est_offset = timedelta(hours=-4) est_offset = timedelta(hours=-4)
est_datetime = utc_datetime + est_offset est_datetime = utc_datetime + est_offset

View File

@@ -4,7 +4,7 @@ from flask import render_template, jsonify
from app import app from app import app
from app.config import SCOREBOARD_DATA_FILE from app.config import SCOREBOARD_DATA_FILE
from app.games import extract_game_info from app.games import parse_games
@app.route("/") @app.route("/")
@@ -27,17 +27,15 @@ def get_scoreboard():
if scoreboard_data: if scoreboard_data:
live_games = [ live_games = [
game game
for game in extract_game_info(scoreboard_data) for game in parse_games(scoreboard_data)
if game["Game State"] == "LIVE" if game["Game State"] == "LIVE"
] ]
pre_games = [ pre_games = [
game game for game in parse_games(scoreboard_data) if game["Game State"] == "PRE"
for game in extract_game_info(scoreboard_data)
if game["Game State"] == "PRE"
] ]
final_games = [ final_games = [
game game
for game in extract_game_info(scoreboard_data) for game in parse_games(scoreboard_data)
if game["Game State"] == "FINAL" if game["Game State"] == "FINAL"
] ]
return jsonify( return jsonify(

View File

@@ -3,15 +3,15 @@ import time
import schedule import schedule
from app.api import store_scoreboard_data from app.api import refresh_scores
from app.standings import update_nhl_standings from app.standings import refresh_standings
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def schedule_tasks(): def start_scheduler():
schedule.every(600).seconds.do(update_nhl_standings) schedule.every(600).seconds.do(refresh_standings)
schedule.every(10).seconds.do(store_scoreboard_data) schedule.every(10).seconds.do(refresh_scores)
logger.info("Background scheduler started") logger.info("Background scheduler started")
while True: while True:
schedule.run_pending() schedule.run_pending()

View File

@@ -26,9 +26,9 @@ def truncate_standings_table(conn):
conn.commit() conn.commit()
def insert_standings_info(conn, standings_info): def insert_standings(conn, standings):
cursor = conn.cursor() cursor = conn.cursor()
for team in standings_info: for team in standings:
cursor.execute( cursor.execute(
""" """
INSERT INTO standings (team_common_name, league_sequence, league_l10_sequence) INSERT INTO standings (team_common_name, league_sequence, league_l10_sequence)
@@ -43,31 +43,32 @@ def insert_standings_info(conn, standings_info):
conn.commit() conn.commit()
def extract_standings_info(): def fetch_standings():
url = "https://api-web.nhle.com/v1/standings/now" url = "https://api-web.nhle.com/v1/standings/now"
try: try:
response = requests.get(url, timeout=10) response = requests.get(url, timeout=10)
response.raise_for_status() response.raise_for_status()
standings_data = response.json() standings_data = response.json()
standings_info = [] standings = []
for team in standings_data.get("standings", []): for team in standings_data.get("standings", []):
team_info = { standings.append(
"team_common_name": team["teamCommonName"]["default"], {
"league_sequence": team["leagueSequence"], "team_common_name": team["teamCommonName"]["default"],
"league_l10_sequence": team["leagueL10Sequence"], "league_sequence": team["leagueSequence"],
} "league_l10_sequence": team["leagueL10Sequence"],
standings_info.append(team_info) }
return standings_info )
return standings
except requests.RequestException as e: except requests.RequestException as e:
logger.error("Failed to fetch standings: %s", e) logger.error("Failed to fetch standings: %s", e)
return None return None
def update_nhl_standings(): def refresh_standings():
conn = sqlite3.connect(DB_PATH) conn = sqlite3.connect(DB_PATH)
create_standings_table(conn) create_standings_table(conn)
truncate_standings_table(conn) truncate_standings_table(conn)
standings_info = extract_standings_info() standings = fetch_standings()
if standings_info: if standings:
insert_standings_info(conn, standings_info) insert_standings(conn, standings)
conn.close() conn.close()

18
run.py
View File

@@ -1,13 +1,15 @@
import threading import threading
from app import app
from app.config import PORT
from app.scheduler import schedule_tasks
from app.api import store_scoreboard_data
from app.standings import update_nhl_standings
from waitress import serve from waitress import serve
from app import app
from app.api import refresh_scores
from app.config import PORT
from app.scheduler import start_scheduler
from app.standings import refresh_standings
if __name__ == "__main__": if __name__ == "__main__":
store_scoreboard_data() refresh_scores()
update_nhl_standings() refresh_standings()
threading.Thread(target=schedule_tasks, daemon=True).start() threading.Thread(target=start_scheduler, daemon=True).start()
serve(app, host="0.0.0.0", port=PORT) serve(app, host="0.0.0.0", port=PORT)

View File

@@ -1,12 +1,12 @@
from tests.conftest import make_game from tests.conftest import make_game
from app.games import ( from app.games import (
convert_game_state, convert_game_state,
format_record,
get_game_outcome, get_game_outcome,
process_period, get_period,
process_record, get_start_time,
process_start_time, get_time_remaining,
process_time_remaining, utc_to_eastern,
utc_to_est_time,
) )
@@ -26,65 +26,65 @@ class TestConvertGameState:
class TestProcessRecord: class TestProcessRecord:
def test_na_returns_na(self): def test_na_returns_na(self):
assert process_record("N/A") == "N/A" assert format_record("N/A") == "N/A"
def test_pads_single_digit_parts(self): def test_pads_single_digit_parts(self):
assert process_record("5-3-1") == "05-03-01" assert format_record("5-3-1") == "05-03-01"
def test_already_padded_unchanged(self): def test_already_padded_unchanged(self):
assert process_record("40-25-10") == "40-25-10" assert format_record("40-25-10") == "40-25-10"
class TestProcessPeriod: class TestProcessPeriod:
def test_pre_game_returns_zero(self): def test_pre_game_returns_zero(self):
game = make_game(game_state="PRE") game = make_game(game_state="PRE")
assert process_period(game) == 0 assert get_period(game) == 0
def test_fut_game_returns_zero(self): def test_fut_game_returns_zero(self):
game = make_game(game_state="FUT") game = make_game(game_state="FUT")
assert process_period(game) == 0 assert get_period(game) == 0
def test_final_game_returns_na(self): def test_final_game_returns_na(self):
game = make_game(game_state="OFF") game = make_game(game_state="OFF")
assert process_period(game) == "N/A" assert get_period(game) == "N/A"
def test_live_game_returns_period_number(self): def test_live_game_returns_period_number(self):
game = make_game(game_state="LIVE", period=2) game = make_game(game_state="LIVE", period=2)
assert process_period(game) == 2 assert get_period(game) == 2
class TestProcessTimeRemaining: class TestProcessTimeRemaining:
def test_pre_game_returns_2000(self): def test_pre_game_returns_2000(self):
game = make_game(game_state="FUT") game = make_game(game_state="FUT")
assert process_time_remaining(game) == "20:00" assert get_time_remaining(game) == "20:00"
def test_final_game_returns_0000(self): def test_final_game_returns_0000(self):
game = make_game(game_state="OFF") game = make_game(game_state="OFF")
assert process_time_remaining(game) == "00:00" assert get_time_remaining(game) == "00:00"
def test_live_game_returns_clock(self): def test_live_game_returns_clock(self):
game = make_game(game_state="LIVE", seconds_remaining=305) game = make_game(game_state="LIVE", seconds_remaining=305)
assert process_time_remaining(game) == "05:05" assert get_time_remaining(game) == "05:05"
def test_live_game_at_zero_returns_end(self): def test_live_game_at_zero_returns_end(self):
game = make_game(game_state="LIVE", seconds_remaining=0) game = make_game(game_state="LIVE", seconds_remaining=0)
assert process_time_remaining(game) == "END" assert get_time_remaining(game) == "END"
class TestProcessStartTime: class TestProcessStartTime:
def test_pre_game_returns_est_time(self): def test_pre_game_returns_est_time(self):
game = make_game(game_state="FUT", start_time_utc="2024-04-10T23:00:00Z") game = make_game(game_state="FUT", start_time_utc="2024-04-10T23:00:00Z")
result = process_start_time(game) result = get_start_time(game)
assert result == "7:00 PM" assert result == "7:00 PM"
def test_pre_game_strips_leading_zero(self): def test_pre_game_strips_leading_zero(self):
game = make_game(game_state="FUT", start_time_utc="2024-04-10T22:00:00Z") game = make_game(game_state="FUT", start_time_utc="2024-04-10T22:00:00Z")
result = process_start_time(game) result = get_start_time(game)
assert not result.startswith("0") assert not result.startswith("0")
def test_live_game_returns_na(self): def test_live_game_returns_na(self):
game = make_game(game_state="LIVE") game = make_game(game_state="LIVE")
assert process_start_time(game) == "N/A" assert get_start_time(game) == "N/A"
class TestGetGameOutcome: class TestGetGameOutcome:
@@ -99,5 +99,5 @@ class TestGetGameOutcome:
class TestUtcToEstTime: class TestUtcToEstTime:
def test_converts_utc_to_est(self): def test_converts_utc_to_est(self):
result = utc_to_est_time("2024-04-10T23:00:00Z") result = utc_to_eastern("2024-04-10T23:00:00Z")
assert result == "07:00 PM" assert result == "07:00 PM"