Files
simple-mensa/api/main.py
T
Matteo Benedetto d592e0f32b feat: Refactor API structure and implement core functionalities
- Updated requirements to include asyncpg, pyyaml, aiofiles, and httpx.
- Modified schema.sql to add 'tipo_pasto' column in 'pasti' table.
- Created .gitignore file to exclude unnecessary files and directories.
- Added README.md for API implementation details and directory structure.
- Introduced config.yaml for centralized configuration management.
- Implemented core modules for database management, authentication, and exception handling.
- Developed models for 'pietanze', 'pasti', and 'prenotazioni' with validation.
- Created routes for CRUD operations on 'pietanze' with pagination and filtering.
- Established logging and error handling mechanisms throughout the application.
- Set up FastAPI application with CORS and health check endpoint.
2025-06-05 18:31:36 +02:00

124 lines
3.3 KiB
Python

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import asyncio
import logging
import yaml
from .core.database import db_manager
from .core.auth import initialize_auth
from .core.exceptions import PietanzaNotFoundError, ValidationError, DatabaseError
from .dependencies import get_config
from .routes import pietanze
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
# Create FastAPI application
app = FastAPI(
title="Simple Mensa API",
description="API for mensa booking system",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc"
)
# Load configuration
config = get_config()
# Configure CORS
app.add_middleware(
CORSMiddleware,
allow_origins=config['cors']['allow_origins'],
allow_credentials=config['cors']['allow_credentials'],
allow_methods=config['cors']['allow_methods'],
allow_headers=config['cors']['allow_headers'],
)
# Include routers
app.include_router(pietanze.router, prefix="/api/v1")
# Exception handlers
@app.exception_handler(PietanzaNotFoundError)
async def pietanza_not_found_handler(request, exc):
return JSONResponse(
status_code=exc.status_code,
content={"error": "Pietanza not found", "detail": exc.detail}
)
@app.exception_handler(ValidationError)
async def validation_error_handler(request, exc):
return JSONResponse(
status_code=exc.status_code,
content={"error": "Validation error", "detail": exc.detail}
)
@app.exception_handler(DatabaseError)
async def database_error_handler(request, exc):
return JSONResponse(
status_code=exc.status_code,
content={"error": "Database error", "detail": exc.detail}
)
# Startup and shutdown events
@app.on_event("startup")
async def startup_event():
"""Initialize application on startup"""
try:
# Initialize database
await db_manager.initialize(config['database'])
logger.info("Database initialized")
# Initialize authentication
initialize_auth(config['auth'])
logger.info("Authentication initialized")
logger.info("Application startup completed")
except Exception as e:
logger.error(f"Failed to initialize application: {e}")
raise
@app.on_event("shutdown")
async def shutdown_event():
"""Cleanup on application shutdown"""
try:
await db_manager.close()
logger.info("Application shutdown completed")
except Exception as e:
logger.error(f"Error during shutdown: {e}")
# Health check endpoint
@app.get("/health")
async def health_check():
"""Health check endpoint"""
return {
"status": "healthy",
"service": "simple-mensa-api",
"version": "1.0.0"
}
# Root endpoint
@app.get("/")
async def root():
"""Root endpoint with API information"""
return {
"message": "Simple Mensa API",
"version": "1.0.0",
"docs": "/docs",
"health": "/health"
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"main:app",
host=config['server']['host'],
port=config['server']['port'],
reload=config['server']['reload'],
debug=config['server']['debug']
)