async chnages to scores and added scores fetching logic to main

This commit is contained in:
Death916 2025-04-24 03:07:02 -07:00
parent 27367934eb
commit 69d546ed6e
2 changed files with 168 additions and 85 deletions

View file

@ -8,7 +8,7 @@ from rxconfig import config
# --- Import your Weather utility ---
from utils.weather import Weather
# from utils.scores import NBAScores, mlbScores
from utils.scores import NBAScores, mlbScores
from utils.news import News
# from utils.alarm import Alarm
import logging
@ -20,29 +20,31 @@ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(
class State(rx.State):
# --- Original state variables (kept as requested) ---
# --- State Variables ---
current_time: str = "" # Note: rx.moment replaces the need for this if used for display
alarm_time: str = ""
alarms: list = []
news: list = [] # Placeholder
nba_scores: str = "" # Placeholder
mlb_scores: str = "" # Placeholder
# --- Weather-specific state variables ---
nba_scores: list = [] # Placeholder
mlb_scores: list = [] # Placeholder
_news_client: News | None = None # This will be set in the constructor
last_weather_update: str = "Never"
weather_img: str = WEATHER_IMAGE_PATH
# Placeholder for the weather client
_weather_client: Weather | None = None # This will be set in the constructor
_mlb_client: list | None = None # This will be set in the constructor
_nba_client: list | None = None # This will be set in the constructor
# --- Initialize Utility Client ---
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Initialize the weather client
try:
self._weather_client = Weather()
self._news_client = News()
self._mlb_client = mlbScores()
self._nba_client = NBAScores()
logging.info("Weather client initialized successfully.")
except Exception as e:
logging.error(f"Failed to initialize Weather client: {e}", exc_info=True)
@ -50,41 +52,85 @@ class State(rx.State):
# Set error state if needed
self.weather_img = "/error_placeholder.png" # Provide a placeholder error image
self.last_weather_update = "Client Init Error"
self.mlb_scores = ""
self.nba_scores = ""
# --- on_load Handler ---
async def start_background_tasks(self):
"""Starts the weather background task when the page loads."""
rx.remove_local_storage("chakra-ui-color-mode")
rx.remove_local_storage("chakra-ui-color-mode") #trying to test themes remove after
logging.info("Triggering background tasks: Weather")
# *** FIX: Return a list containing the handler reference ***
return [State.fetch_weather]
return [State.fetch_weather, State.fetch_sports]
# --- Sports Background Task ---
@rx.event(background=True)
async def fetch_news(self):
"""Fetches news periodically."""
# Placeholder for the actual news fetching logic
async def fetch_sports(self):
# Fetches sports scores periodically
while True:
try:
logging.info("Fetching news...")
news_items = await self._news_client.get_news() # This now comes from utils/news.py
if not news_items:
logging.warning("No news items fetched.")
logging.info("Fetching sports scores...")
# Fetch MLB and NBA scores
mlb_scores = await self._mlb_client.get_scores()
logging.info(f"MLB Scores: {mlb_scores}")
# Check if MLB scores are empty
if not mlb_scores:
logging.warning("No MLB scores fetched.")
async with self:
self.news = []
yield # Update frontend
else:
logging.info(f"Fetched {len(news_items)} news items.")
async with self:
self.news = news_items
self.mlb_scores = []
yield
nba_scores = await self._nba_client.get_scores()
logging.info(f"NBA Scores: {nba_scores}")
# Check if NBA scores are empty
if not nba_scores:
logging.warning("No NBA scores fetched.")
async with self:
self.nba_scores = []
yield
# Update state with fetched scores
async with self:
self.mlb_scores = mlb_scores
self.nba_scores = nba_scores
logging.info(f"Fetched {len(mlb_scores)} MLB scores and {len(nba_scores)} NBA scores.")
yield # Update frontend
except Exception as e:
logging.error(f"Error in fetch_news background task: {e}", exc_info=True)
logging.error(f"Error in fetch_sports background task: {e}", exc_info=True)
await asyncio.sleep(500)
# format sports scores for display
"""
@rx.event(background=True)
async def fetch_news(self):
#Fetches news periodically
# Placeholder for the actual news fetching logic
while True:
try:
logging.info("Fetching news...")
news_items = await self._news_client.get_news()
if not news_items:
logging.warning("No news items fetched.")
async with self:
self.news = []
yield # Update frontend
else:
logging.info(f"Fetched {len(news_items)} news items.")
async with self:
self.news = news_items
yield
except Exception as e:
logging.error(f"Error in fetch_news background task: {e}", exc_info=True)
await asyncio.sleep(500)
"""
# --- Weather Background Task ---
@rx.event(background=True)
async def fetch_weather(self):
@ -92,7 +138,7 @@ class State(rx.State):
# Check if the client initialized correctly
if not hasattr(self, '_weather_client') or self._weather_client is None:
logging.warning("Weather client not initialized. Stopping fetch_weather task.")
# Optionally update state to reflect this persistent error
async with self:
self.last_weather_update = "Error: Weather client unavailable"
yield
@ -102,7 +148,7 @@ class State(rx.State):
try:
logging.info("Attempting to fetch weather screenshot...")
# Call the method from the initialized client
img_web_path = self._weather_client.get_weather_screenshot() # This now comes from utils/weather.py
img_web_path = self._weather_client.get_weather_screenshot()
if img_web_path:
async with self:
@ -124,8 +170,6 @@ class State(rx.State):
logging.error(f"Error in fetch_weather background task: {e}", exc_info=True)
async with self: # Update state to show error
self.last_weather_update = f"Error @ {datetime.now(timezone.utc).strftime('%H:%M:%S UTC')}"
# Optionally reset image to placeholder on error
# self.weather_img = WEATHER_IMAGE_PATH
yield
await asyncio.sleep(WEATHER_FETCH_INTERVAL)
@ -238,4 +282,4 @@ app.add_page(
# The original TypeError is resolved by returning [State.fetch_weather]
# from State.start_background_tasks.
# The image display is fixed by binding rx.image src to State.weather_img.
# The image display is fixed by binding rx.image src to State.weather_img.