import requests import os import random from typing import Optional, Dict from utils.config import config class NasaService: """Service for fetching NASA data including space weather""" def __init__(self): self.api_key = config.nasa_api_key or os.getenv("NASA_API_KEY") self.base_url = "https://api.nasa.gov" def get_apod(self) -> Optional[Dict]: """Get Astronomy Picture of the Day""" if not self.api_key: return None try: params = { 'api_key': self.api_key, 'thumbs': 'true' } response = requests.get( f"{self.base_url}/planetary/apod", params=params, timeout=10 ) if response.status_code == 200: return response.json() return None except Exception as e: print(f"Error fetching APOD: {e}") return None def get_space_weather_alerts(self) -> Optional[Dict]: """Get space weather alerts""" try: response = requests.get( f"{self.base_url}/DONKI/notifications", params={'api_key': self.api_key or 'DEMO_KEY'}, timeout=10 ) if response.status_code == 200: data = response.json() # Get recent alerts (last 7 days) if isinstance(data, list) and len(data) > 0: return data[0] # Most recent alert return None except Exception as e: print(f"Error fetching space weather: {e}") return None def get_mars_weather(self) -> Optional[Dict]: """Get Mars weather data""" try: response = requests.get( f"{self.base_url}/insight_weather/", params={ 'api_key': self.api_key or 'DEMO_KEY', 'feedtype': 'json', 'ver': '1.0' }, timeout=10 ) if response.status_code == 200: return response.json() return None except Exception as e: print(f"Error fetching Mars weather: {e}") return None # Global instance nasa_service = NasaService()