app backend prima
This commit is contained in:
107
app/main.py
Normal file
107
app/main.py
Normal file
@@ -0,0 +1,107 @@
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.database import Base, engine
|
||||
from app.api import auth, allarmi, siti, statistiche
|
||||
from app.mqtt.client import MQTTClient
|
||||
from app.mqtt.handler import alarm_handler
|
||||
|
||||
# Configurazione logging
|
||||
logging.basicConfig(
|
||||
level=logging.INFO if not settings.DEBUG else logging.DEBUG,
|
||||
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Client MQTT globale
|
||||
mqtt_client = None
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""Gestione lifecycle dell'applicazione"""
|
||||
global mqtt_client
|
||||
|
||||
# Startup
|
||||
logger.info("Avvio applicazione...")
|
||||
|
||||
# Crea tabelle database
|
||||
logger.info("Creazione tabelle database...")
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
# Avvia client MQTT
|
||||
logger.info("Avvio client MQTT...")
|
||||
mqtt_client = MQTTClient(message_handler=alarm_handler.handle_alarm)
|
||||
try:
|
||||
mqtt_client.start()
|
||||
logger.info("Client MQTT avviato con successo")
|
||||
except Exception as e:
|
||||
logger.error(f"Errore nell'avvio del client MQTT: {e}")
|
||||
logger.warning("L'applicazione continuerà senza il client MQTT")
|
||||
|
||||
yield
|
||||
|
||||
# Shutdown
|
||||
logger.info("Arresto applicazione...")
|
||||
if mqtt_client:
|
||||
mqtt_client.stop()
|
||||
logger.info("Client MQTT fermato")
|
||||
|
||||
|
||||
# Crea applicazione FastAPI
|
||||
app = FastAPI(
|
||||
title=settings.APP_NAME,
|
||||
description="API per il sistema di monitoraggio terreni con notifiche push",
|
||||
version="1.0.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
# Configurazione CORS
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"], # In produzione, specificare i domini permessi
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Registrazione router
|
||||
app.include_router(auth.router)
|
||||
app.include_router(allarmi.router)
|
||||
app.include_router(siti.router)
|
||||
app.include_router(statistiche.router)
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
"""Endpoint root per verificare che l'API sia attiva"""
|
||||
return {
|
||||
"message": "Terrain Monitor API",
|
||||
"version": "1.0.0",
|
||||
"status": "active",
|
||||
}
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
"""Health check endpoint"""
|
||||
return {
|
||||
"status": "healthy",
|
||||
"mqtt_connected": mqtt_client.client.is_connected() if mqtt_client else False,
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run(
|
||||
"app.main:app",
|
||||
host="0.0.0.0",
|
||||
port=8000,
|
||||
reload=settings.DEBUG,
|
||||
)
|
||||
Reference in New Issue
Block a user