Files
bakery-ia/services/data/app/api/weather.py

183 lines
7.2 KiB
Python
Raw Normal View History

2025-07-18 11:51:43 +02:00
# ================================================================
2025-07-19 12:09:10 +02:00
# services/data/app/api/weather.py - FIXED VERSION
2025-07-18 11:51:43 +02:00
# ================================================================
2025-07-19 12:09:10 +02:00
"""Weather data API endpoints with improved error handling"""
2025-07-18 11:51:43 +02:00
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List, Optional
from datetime import datetime, timedelta
2025-07-19 12:09:10 +02:00
import structlog
2025-07-18 11:51:43 +02:00
from app.core.database import get_db
2025-07-18 16:48:49 +02:00
from app.core.auth import get_current_user, AuthInfo
2025-07-18 11:51:43 +02:00
from app.services.weather_service import WeatherService
2025-07-19 12:51:28 +02:00
from app.services.messaging import publish_weather_updated
2025-07-18 11:51:43 +02:00
from app.schemas.external import (
WeatherDataResponse,
WeatherForecastResponse,
LocationRequest,
DateRangeRequest
)
router = APIRouter()
weather_service = WeatherService()
2025-07-19 12:09:10 +02:00
logger = structlog.get_logger()
2025-07-18 11:51:43 +02:00
@router.get("/current", response_model=WeatherDataResponse)
async def get_current_weather(
latitude: float = Query(..., description="Latitude"),
longitude: float = Query(..., description="Longitude"),
2025-07-18 16:48:49 +02:00
current_user: AuthInfo = Depends(get_current_user)
2025-07-18 11:51:43 +02:00
):
"""Get current weather for location"""
try:
2025-07-19 12:09:10 +02:00
logger.debug("API: Getting current weather", lat=latitude, lon=longitude)
2025-07-18 11:51:43 +02:00
weather = await weather_service.get_current_weather(latitude, longitude)
2025-07-19 12:09:10 +02:00
2025-07-18 11:51:43 +02:00
if not weather:
2025-07-19 12:09:10 +02:00
logger.warning("No weather data available", lat=latitude, lon=longitude)
2025-07-18 11:51:43 +02:00
raise HTTPException(status_code=404, detail="Weather data not available")
2025-07-19 12:09:10 +02:00
logger.debug("Successfully returning weather data", temp=weather.temperature)
2025-07-18 11:51:43 +02:00
return weather
2025-07-19 12:09:10 +02:00
except HTTPException:
# Re-raise HTTP exceptions
raise
2025-07-18 11:51:43 +02:00
except Exception as e:
2025-07-19 12:09:10 +02:00
logger.error("Unexpected error in weather API", error=str(e))
import traceback
logger.error("Weather API traceback", traceback=traceback.format_exc())
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
2025-07-18 11:51:43 +02:00
@router.get("/forecast", response_model=List[WeatherForecastResponse])
async def get_weather_forecast(
latitude: float = Query(..., description="Latitude"),
longitude: float = Query(..., description="Longitude"),
days: int = Query(7, description="Number of forecast days", ge=1, le=14),
2025-07-18 16:48:49 +02:00
current_user: AuthInfo = Depends(get_current_user)
2025-07-18 11:51:43 +02:00
):
"""Get weather forecast for location"""
try:
2025-07-19 12:09:10 +02:00
logger.debug("API: Getting weather forecast", lat=latitude, lon=longitude, days=days)
2025-07-18 11:51:43 +02:00
forecast = await weather_service.get_weather_forecast(latitude, longitude, days)
2025-07-19 12:09:10 +02:00
if not forecast:
logger.warning("No forecast data available", lat=latitude, lon=longitude)
raise HTTPException(status_code=404, detail="Weather forecast not available")
# Publish event (with error handling)
try:
2025-07-19 12:51:28 +02:00
await publish_weather_updated({
2025-07-19 12:09:10 +02:00
"type": "forecast_requested",
"latitude": latitude,
"longitude": longitude,
"days": days,
"timestamp": datetime.utcnow().isoformat()
})
except Exception as pub_error:
logger.warning("Failed to publish weather forecast event", error=str(pub_error))
# Continue processing - event publishing failure shouldn't break the API
2025-07-18 11:51:43 +02:00
2025-07-19 12:09:10 +02:00
logger.debug("Successfully returning forecast data", count=len(forecast))
2025-07-18 11:51:43 +02:00
return forecast
2025-07-19 12:09:10 +02:00
except HTTPException:
# Re-raise HTTP exceptions
raise
2025-07-18 11:51:43 +02:00
except Exception as e:
2025-07-19 12:09:10 +02:00
logger.error("Unexpected error in weather forecast API", error=str(e))
import traceback
logger.error("Weather forecast API traceback", traceback=traceback.format_exc())
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
2025-07-18 11:51:43 +02:00
@router.get("/historical", response_model=List[WeatherDataResponse])
async def get_historical_weather(
latitude: float = Query(..., description="Latitude"),
longitude: float = Query(..., description="Longitude"),
start_date: datetime = Query(..., description="Start date"),
end_date: datetime = Query(..., description="End date"),
db: AsyncSession = Depends(get_db),
2025-07-18 16:48:49 +02:00
current_user: AuthInfo = Depends(get_current_user)
2025-07-18 11:51:43 +02:00
):
"""Get historical weather data"""
try:
# Validate date range
if end_date <= start_date:
raise HTTPException(status_code=400, detail="End date must be after start date")
if (end_date - start_date).days > 365:
raise HTTPException(status_code=400, detail="Date range cannot exceed 365 days")
historical_data = await weather_service.get_historical_weather(
latitude, longitude, start_date, end_date, db
)
2025-07-19 12:09:10 +02:00
# Publish event (with error handling)
try:
2025-07-19 12:51:28 +02:00
await publish_weather_updated({
2025-07-19 12:09:10 +02:00
"type": "historical_requested",
"latitude": latitude,
"longitude": longitude,
"start_date": start_date.isoformat(),
"end_date": end_date.isoformat(),
"records_count": len(historical_data),
"timestamp": datetime.utcnow().isoformat()
})
except Exception as pub_error:
logger.warning("Failed to publish historical weather event", error=str(pub_error))
# Continue processing
2025-07-18 11:51:43 +02:00
return historical_data
2025-07-19 12:09:10 +02:00
except HTTPException:
# Re-raise HTTP exceptions
raise
except Exception as e:
logger.error("Unexpected error in historical weather API", error=str(e))
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
@router.post("/store")
async def store_weather_data(
latitude: float = Query(..., description="Latitude"),
longitude: float = Query(..., description="Longitude"),
db: AsyncSession = Depends(get_db),
current_user: AuthInfo = Depends(get_current_user)
):
"""Store current weather data to database"""
try:
# Get current weather data
weather = await weather_service.get_current_weather(latitude, longitude)
if not weather:
raise HTTPException(status_code=404, detail="No weather data to store")
# Convert to dict for storage
weather_dict = {
"date": weather.date,
"temperature": weather.temperature,
"precipitation": weather.precipitation,
"humidity": weather.humidity,
"wind_speed": weather.wind_speed,
"pressure": weather.pressure,
"description": weather.description,
"source": weather.source
}
success = await weather_service.store_weather_data(
latitude, longitude, weather_dict, db
)
if success:
return {"status": "success", "message": "Weather data stored successfully"}
else:
raise HTTPException(status_code=500, detail="Failed to store weather data")
except HTTPException:
raise
2025-07-18 11:51:43 +02:00
except Exception as e:
2025-07-19 12:09:10 +02:00
logger.error("Error storing weather data", error=str(e))
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")