Spaces:
Runtime error
Runtime error
File size: 6,203 Bytes
30be4c2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | """
Example FastAPI endpoints showing how to use the database models and queries.
This is a reference file - integrate these patterns into your FastAPI app.
"""
from typing import List
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
from .database import get_db
from .models import SpeedCamera, RoadSpeedLimit, HazardDetection
from .queries import (
get_nearby_speed_cameras,
get_nearby_speed_limits,
get_nearby_hazards,
create_speed_camera,
create_road_speed_limit,
)
router = APIRouter(prefix="/api/v1", tags=["navigation"])
# ============================================
# Pydantic Models for Request/Response
# ============================================
class SpeedCameraResponse(BaseModel):
id: UUID
latitude: float
longitude: float
speed_limit_kmh: int
camera_type: str
direction_degrees: int | None
verified: bool
confidence_score: float
class Config:
from_attributes = True
class RoadSpeedLimitResponse(BaseModel):
id: UUID
speed_limit_kmh: int
road_name: str | None
road_type: str | None
verified: bool
confidence_score: float
class Config:
from_attributes = True
class HazardResponse(BaseModel):
id: UUID
latitude: float
longitude: float
hazard_type: str
severity: str
confidence_score: float
is_active: bool
class Config:
from_attributes = True
class CreateSpeedCameraRequest(BaseModel):
latitude: float = Field(..., ge=-90, le=90)
longitude: float = Field(..., ge=-180, le=180)
speed_limit_kmh: int = Field(..., gt=0, le=200)
camera_type: str = Field(..., pattern="^(fixed|mobile|average_speed)$")
direction_degrees: int | None = Field(None, ge=0, le=360)
confidence_score: float = Field(0.50, ge=0.0, le=1.0)
notes: str | None = None
# ============================================
# Example Endpoints
# ============================================
@router.get("/cameras/nearby", response_model=List[SpeedCameraResponse])
async def get_cameras_nearby(
latitude: float = Query(..., ge=-90, le=90, description="Latitude"),
longitude: float = Query(..., ge=-180, le=180, description="Longitude"),
radius_meters: float = Query(1000.0, gt=0, le=10000, description="Search radius in meters"),
min_confidence: float = Query(0.0, ge=0.0, le=1.0, description="Minimum confidence score"),
verified_only: bool = Query(False, description="Only return verified cameras"),
db: AsyncSession = Depends(get_db),
):
"""
Get speed cameras near a location.
"""
cameras = await get_nearby_speed_cameras(
db=db,
latitude=latitude,
longitude=longitude,
radius_meters=radius_meters,
min_confidence=min_confidence,
verified_only=verified_only,
)
# Convert to response format
# Note: You'll need to extract lat/lon from the PostGIS geometry
# This is a simplified example - you may want to add a helper function
return cameras
@router.get("/speed-limits/nearby", response_model=List[RoadSpeedLimitResponse])
async def get_speed_limits_nearby(
latitude: float = Query(..., ge=-90, le=90),
longitude: float = Query(..., ge=-180, le=180),
radius_meters: float = Query(500.0, gt=0, le=5000),
min_confidence: float = Query(0.0, ge=0.0, le=1.0),
verified_only: bool = Query(False),
db: AsyncSession = Depends(get_db),
):
"""
Get road speed limits near a location.
"""
speed_limits = await get_nearby_speed_limits(
db=db,
latitude=latitude,
longitude=longitude,
radius_meters=radius_meters,
min_confidence=min_confidence,
verified_only=verified_only,
)
return speed_limits
@router.get("/hazards/nearby", response_model=List[HazardResponse])
async def get_hazards_nearby(
latitude: float = Query(..., ge=-90, le=90),
longitude: float = Query(..., ge=-180, le=180),
radius_meters: float = Query(1000.0, gt=0, le=10000),
min_confidence: float = Query(0.0, ge=0.0, le=1.0),
active_only: bool = Query(True),
db: AsyncSession = Depends(get_db),
):
"""
Get active hazards near a location.
"""
hazards = await get_nearby_hazards(
db=db,
latitude=latitude,
longitude=longitude,
radius_meters=radius_meters,
min_confidence=min_confidence,
active_only=active_only,
)
return hazards
@router.post("/cameras", response_model=SpeedCameraResponse, status_code=201)
async def create_camera(
request: CreateSpeedCameraRequest,
# In production, get user_id from JWT token
# user_id: UUID = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db),
):
"""
Create a new speed camera report.
"""
camera = await create_speed_camera(
db=db,
latitude=request.latitude,
longitude=request.longitude,
speed_limit_kmh=request.speed_limit_kmh,
camera_type=request.camera_type,
direction_degrees=request.direction_degrees,
confidence_score=request.confidence_score,
# reported_by=user_id, # Uncomment when auth is implemented
notes=request.notes,
)
await db.commit()
return camera
# ============================================
# Example FastAPI App Setup
# ============================================
"""
# In your main FastAPI app (e.g., main.py):
from fastapi import FastAPI
from database import init_db, close_db
from database.example_usage import router as navigation_router
app = FastAPI(title="Navigation App API")
# Include routers
app.include_router(navigation_router)
@app.on_event("startup")
async def startup():
# Initialize database tables
await init_db()
@app.on_event("shutdown")
async def shutdown():
# Close database connections
await close_db()
@app.get("/health")
async def health_check():
from database import check_db_health
db_healthy = await check_db_health()
return {"status": "healthy" if db_healthy else "unhealthy", "database": db_healthy}
"""
|