33Handles fetching, validation, and display of astronomical data.
44"""
55
6- import json
76import time
87from datetime import date
98
10- import httpx
11- from pydantic import ValidationError
12-
139from sample_python_app .core import (
1410 FETCH_COUNTER ,
1511 FETCH_DURATION ,
16- FETCH_ERRORS ,
1712 setup_logger ,
1813 weather_settings ,
1914)
@@ -41,30 +36,31 @@ def __init__(self, client: CustomHTTPClient) -> None:
4136 self .client = client
4237
4338 def fetch (self , * , exit_on_error : bool = True ) -> None :
44- """Fetch astronomical data and display if not already displayed today."""
39+ """Fetch astronomical data and display if not already shown today."""
4540 lat = weather_settings .LOCATION .latitude
4641 lon = weather_settings .LOCATION .longitude
47- logger .info (f"Using latitude={ lat } longitude={ lon } " )
42+
43+ logger .info ("Using latitude=%s longitude=%s" , lat , lon )
44+
4845 start = time .time ()
46+
4947 try :
5048 astro = fetch_astronomical_data_from_api (lat , lon , client = self .client )
5149 forecast = fetch_hourly_forecast_from_api (lat , lon , client = self .client )
5250 FETCH_COUNTER .inc ()
53- except (
54- httpx .HTTPStatusError ,
55- httpx .RequestError ,
56- ValidationError ,
57- json .JSONDecodeError ,
58- AppError ,
59- ) as exc :
60- self ._handle_fetch_error (exc , exit_on_error )
51+ except AppError as exc :
52+ logger .error ("Weather fetch failed: %s" , exc )
53+ if exit_on_error :
54+ raise SystemExit (1 ) from None
6155 return
6256 finally :
6357 FETCH_DURATION .observe (time .time () - start )
64- today_str = date .today ().isoformat ()
65- if self ._last_displayed_day != today_str :
58+
59+ today = date .today ().isoformat ()
60+
61+ if self ._last_displayed_day != today :
6662 display_astronomical_data (astro , forecast )
67- self ._last_displayed_day = today_str
63+ self ._last_displayed_day = today
6864
6965 def reset_display (self ):
7066 """Reset the last displayed day so display will occur again."""
@@ -82,22 +78,6 @@ def close(self) -> None:
8278 except Exception :
8379 logger .exception ("Error closing HTTP client in AstroFetcher" )
8480
85- def _handle_fetch_error (self , exc : Exception , exit_on_error : bool ) -> None :
86- FETCH_ERRORS .inc ()
87- if isinstance (exc , httpx .HTTPStatusError ):
88- logger .error ("HTTP status error: %s" , exc )
89- elif isinstance (exc , httpx .RequestError ):
90- logger .error ("Network error: %s" , exc )
91- elif isinstance (exc , ValidationError ):
92- logger .error ("Validation error: %s" , exc )
93- elif isinstance (exc , json .JSONDecodeError ):
94- logger .error ("JSON decode error: %s" , exc )
95- else :
96- logger .exception ("Unexpected error" )
97- if exit_on_error :
98- raise SystemExit (1 ) from exc
99- raise AppError (str (exc )) from exc
100-
10181
10282runner_client = CustomHTTPClient (
10383 headers = weather_settings .WEATHER_HEADERS ,
0 commit comments