|
| 1 | +"""Runner module for the sample Python app. |
| 2 | +
|
| 3 | +Handles fetching, validation, and display of astronomical data. |
| 4 | +""" |
| 5 | + |
| 6 | +# app/runner.py |
| 7 | +import json |
| 8 | +import time |
| 9 | + |
| 10 | +import httpx |
| 11 | +from pydantic import ValidationError |
| 12 | + |
| 13 | +from sample_python_app.core import ( |
| 14 | + FETCH_COUNTER, |
| 15 | + FETCH_DURATION, |
| 16 | + FETCH_ERRORS, |
| 17 | + display_astronomical_data, |
| 18 | + setup_logger, |
| 19 | + weather_settings, |
| 20 | +) |
| 21 | +from sample_python_app.exceptions import AppError |
| 22 | +from sample_python_app.services import fetch_astronomical_data_from_api |
| 23 | + |
| 24 | +logger = setup_logger("normal") |
| 25 | + |
| 26 | + |
| 27 | +def fetch_astro_data(*, exit_on_error: bool = True) -> None: |
| 28 | + """Fetch and display astronomical data once, with error handling.""" |
| 29 | + lat = weather_settings.LOCATION.latitude |
| 30 | + lon = weather_settings.LOCATION.longitude |
| 31 | + logger.info(f"Using latitude={lat} longitude={lon}") |
| 32 | + |
| 33 | + start = time.time() |
| 34 | + |
| 35 | + try: |
| 36 | + astro = fetch_astronomical_data_from_api(lat, lon) |
| 37 | + FETCH_COUNTER.inc() |
| 38 | + except httpx.HTTPStatusError as exc: |
| 39 | + _handle_fetch_error(exc, exit_on_error) |
| 40 | + return |
| 41 | + except httpx.RequestError as exc: |
| 42 | + _handle_fetch_error(exc, exit_on_error) |
| 43 | + return |
| 44 | + except ValidationError as exc: |
| 45 | + _handle_fetch_error(exc, exit_on_error) |
| 46 | + return |
| 47 | + except json.JSONDecodeError as exc: |
| 48 | + _handle_fetch_error(exc, exit_on_error) |
| 49 | + return |
| 50 | + except AppError as exc: |
| 51 | + _handle_fetch_error(exc, exit_on_error) |
| 52 | + return |
| 53 | + finally: |
| 54 | + FETCH_DURATION.observe(time.time() - start) |
| 55 | + |
| 56 | + display_astronomical_data(astro) |
| 57 | + |
| 58 | + |
| 59 | +def _handle_fetch_error(exc: Exception, exit_on_error: bool) -> None: |
| 60 | + """Handle errors during the fetch operation. |
| 61 | +
|
| 62 | + Log appropriately and update metrics. |
| 63 | + """ |
| 64 | + FETCH_ERRORS.inc() |
| 65 | + if isinstance(exc, httpx.HTTPStatusError): |
| 66 | + logger.error("HTTP status error: %s", exc) |
| 67 | + elif isinstance(exc, httpx.RequestError): |
| 68 | + logger.error("Network error: %s", exc) |
| 69 | + elif isinstance(exc, ValidationError): |
| 70 | + logger.error("Validation error: %s", exc) |
| 71 | + elif isinstance(exc, json.JSONDecodeError): |
| 72 | + logger.error("JSON decode error: %s", exc) |
| 73 | + else: |
| 74 | + logger.exception("Unexpected error") |
| 75 | + |
| 76 | + if exit_on_error: |
| 77 | + raise SystemExit(1) from exc |
| 78 | + |
| 79 | + raise AppError(str(exc)) from exc |
0 commit comments