Files
bakery-ia/services/data/app/api/traffic.py
2025-07-18 16:48:49 +02:00

83 lines
3.1 KiB
Python

# ================================================================
# services/data/app/api/traffic.py
# ================================================================
"""Traffic data API endpoints"""
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List, Optional
from datetime import datetime, timedelta
from app.core.database import get_db
from app.core.auth import get_current_user, AuthInfo
from app.services.traffic_service import TrafficService
from app.services.messaging import data_publisher
from app.schemas.external import (
TrafficDataResponse,
LocationRequest,
DateRangeRequest
)
router = APIRouter()
traffic_service = TrafficService()
@router.get("/current", response_model=TrafficDataResponse)
async def get_current_traffic(
latitude: float = Query(..., description="Latitude"),
longitude: float = Query(..., description="Longitude"),
current_user: AuthInfo = Depends(get_current_user)
):
"""Get current traffic data for location"""
try:
traffic = await traffic_service.get_current_traffic(latitude, longitude)
if not traffic:
raise HTTPException(status_code=404, detail="Traffic data not available")
# Publish event
await data_publisher.publish_traffic_updated({
"type": "current_requested",
"latitude": latitude,
"longitude": longitude,
"timestamp": datetime.utcnow().isoformat()
})
return traffic
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.get("/historical", response_model=List[TrafficDataResponse])
async def get_historical_traffic(
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),
current_user: AuthInfo = Depends(get_current_user)
):
"""Get historical traffic 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 > 90:
raise HTTPException(status_code=400, detail="Date range cannot exceed 90 days")
historical_data = await traffic_service.get_historical_traffic(
latitude, longitude, start_date, end_date, db
)
# Publish event
await data_publisher.publish_traffic_updated({
"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()
})
return historical_data
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))