Files
bakery-ia/services/data/app/main.py
Urtzi Alfaro 592a810762 Fix issues
2025-07-18 11:51:43 +02:00

73 lines
2.1 KiB
Python

"""
Data Service Main Application
Handles external API integrations (weather, traffic, events)
"""
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import structlog
from app.core.config import settings
from app.core.database import init_db
from app.api.sales import router as sales_router
from app.api.weather import router as weather_router
from app.api.traffic import router as traffic_router
from shared.monitoring.metrics import setup_metrics
from shared.monitoring.logging import setup_logging
# Setup logging
setup_logging("data-service", settings.LOG_LEVEL)
logger = structlog.get_logger()
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Application lifespan events"""
# Startup
logger.info("Starting Data Service")
await init_db()
yield
# Shutdown
logger.info("Shutting down Data Service")
# Create FastAPI app
app = FastAPI(
title="Bakery Data Service",
description="External data integration service for weather, traffic, and sales data",
version="1.0.0",
lifespan=lifespan
)
# Setup metrics
setup_metrics(app)
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include routers
app.include_router(sales_router, prefix="/api/v1/sales", tags=["sales"])
app.include_router(weather_router, prefix="/api/v1/weather", tags=["weather"])
app.include_router(traffic_router, prefix="/api/v1/traffic", tags=["traffic"])
@app.get("/health")
async def health_check():
"""Health check endpoint"""
return {"status": "healthy", "service": "data-service"}
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
"""Global exception handler"""
logger.error("Unhandled exception", exc_info=exc, path=request.url.path)
return JSONResponse(
status_code=500,
content={"detail": "Internal server error"}
)