Files
Dashboard_Projects_Management/dashboard/weather.py
T
2026-10-15 20:38:02 +02:00

91 lines
3.7 KiB
Python

"""Open-Meteo adapter. No user location is persisted or logged."""
import hashlib
import json
import math
from datetime import datetime, timezone
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from django.core.cache import caches
ENDPOINT = "https://api.open-meteo.com/v1/forecast"
CURRENT = (
"temperature_2m", "apparent_temperature", "relative_humidity_2m", "weather_code",
"precipitation", "wind_speed_10m", "wind_direction_10m", "cloud_cover", "is_day",
)
HOURLY = (
"temperature_2m", "apparent_temperature", "precipitation", "precipitation_probability",
"wind_speed_10m", "wind_gusts_10m", "wind_direction_10m", "relative_humidity_2m",
"cloud_cover", "uv_index", "weather_code", "is_day",
)
DAILY = (
"temperature_2m_max", "temperature_2m_min", "sunrise", "sunset", "daylight_duration",
"precipitation_sum", "precipitation_probability_max", "wind_gusts_10m_max", "uv_index_max", "snowfall_sum",
)
FRESH_SECONDS = 900
STALE_SECONDS = 3600
class ForecastUnavailable(Exception):
pass
def coordinates(latitude, longitude):
try:
lat, lon = float(latitude), float(longitude)
except (TypeError, ValueError):
raise ValueError("Invalid coordinates") from None
if not math.isfinite(lat) or not math.isfinite(lon) or not (-90 <= lat <= 90) or not (-180 <= lon <= 180):
raise ValueError("Invalid coordinates")
return round(lat, 2), round(lon, 2)
def request_forecast(lat, lon):
params = {
"latitude": lat, "longitude": lon, "timezone": "auto", "forecast_hours": 48,
"forecast_days": 2, "temperature_unit": "celsius", "wind_speed_unit": "kmh",
"precipitation_unit": "mm", "current": ",".join(CURRENT),
"hourly": ",".join(HOURLY), "daily": ",".join(DAILY),
}
request = Request(f"{ENDPOINT}?{urlencode(params)}", headers={"User-Agent": "CommonGroundDashboard/1.0"})
with urlopen(request, timeout=8) as response:
if response.status != 200:
raise ForecastUnavailable("Weather service is temporarily unavailable")
payload = json.load(response)
if payload.get("error") or not all(isinstance(payload.get(key), dict) for key in ("current", "hourly", "daily")):
raise ForecastUnavailable("Weather data could not be read")
if not isinstance(payload["hourly"].get("time"), list) or not payload["hourly"]["time"]:
raise ForecastUnavailable("Hourly forecast is unavailable")
return {
"current": payload["current"], "hourly": payload["hourly"], "daily": payload["daily"],
"timezone": payload.get("timezone_abbreviation") or payload.get("timezone") or "local time",
"fetched_at": datetime.now(timezone.utc).isoformat(),
}
def get_forecast(latitude, longitude):
lat, lon = coordinates(latitude, longitude)
key = hashlib.sha256(f"open-meteo:v1:{lat:.2f}:{lon:.2f}".encode()).hexdigest()
cache = caches["weather"]
fresh = cache.get(f"fresh:{key}")
if fresh is not None:
return {**fresh, "stale": False}
stale = cache.get(f"stale:{key}")
lock = f"lock:{key}"
if not cache.add(lock, True, timeout=20):
if stale is not None:
return {**stale, "stale": True}
raise ForecastUnavailable("Forecast is being refreshed. Try again shortly")
try:
payload = request_forecast(lat, lon)
cache.set(f"fresh:{key}", payload, timeout=FRESH_SECONDS)
cache.set(f"stale:{key}", payload, timeout=STALE_SECONDS)
return {**payload, "stale": False}
except (OSError, ValueError, json.JSONDecodeError, ForecastUnavailable) as exc:
if stale is not None:
return {**stale, "stale": True}
raise ForecastUnavailable("Weather service is temporarily unavailable") from exc
finally:
cache.delete(lock)