61 lines
2.2 KiB
Python
61 lines
2.2 KiB
Python
from weathersettings import (HEADERS, NOMINATIM_URL, API_BASE_URL,
|
|
requests, logger, Optional, Tuple, Dict, List,
|
|
json
|
|
)
|
|
|
|
|
|
# Get and translate Town/City State name to coordinates
|
|
def get_coordinates_from_location(location_name):
|
|
params = {
|
|
"q": location_name,
|
|
"format": "json",
|
|
"limit": 1,
|
|
}
|
|
try:
|
|
response = requests.get(NOMINATIM_URL, params=params, headers=HEADERS)
|
|
response.raise_for_status()
|
|
data = response.json()
|
|
if data:
|
|
print(f"\n")
|
|
logger.info(f"Location data fetched for {location_name}")
|
|
return float(data[0]['lat']), float(data[0]['lon'])
|
|
else:
|
|
logger.warning(f"No location data found for {location_name}")
|
|
except requests.RequestException as e:
|
|
logger.error(f"Error fetching location data: {e}")
|
|
return None
|
|
|
|
|
|
# uses the fetched data to find the weather.gov grid point
|
|
def get_gridpoint_forecast(lat: float, lon: float) -> Optional[str]:
|
|
points_url = f"{API_BASE_URL}points/{lat},{lon}"
|
|
try:
|
|
response = requests.get(points_url, headers=HEADERS)
|
|
response.raise_for_status()
|
|
data = response.json()
|
|
logger.info(f"Gridpoint forecast fetched for coordinates {lat}, {lon}")
|
|
return data['properties']['forecast']
|
|
|
|
except requests.RequestException as e:
|
|
logger.error(f"Error fetching gridpoint forecast: {e}")
|
|
return None
|
|
|
|
|
|
# get forecast data from URL if gridpoint fetch succeeded
|
|
def get_forecast(forecast_url):
|
|
try:
|
|
response = requests.get(forecast_url, headers=HEADERS)
|
|
response.raise_for_status()
|
|
data = response.json()
|
|
logger.info(f"Forecast data retrieved from {forecast_url}")
|
|
return data
|
|
except requests.RequestException as e:
|
|
logger.error(f"Error fetching forecast data: {e}")
|
|
return None
|
|
|
|
|
|
# Saves the forecast data
|
|
def save_data(formatted_data: List[Dict]):
|
|
"""Saves the formatted forecast data to a JSON file."""
|
|
with open('forecast_data.json', 'w') as f:
|
|
json.dump(formatted_data, f) |