Files
mtgonline/backend/app/main.py
T

114 lines
3.4 KiB
Python

"""
MTG Online Backend Application
FastAPI application for the MTG Online multiplayer platform.
Mounts all routers and provides centralized configuration.
## Routers
- Authentication: /auth/*
- Users: /users/*
- Decks: /decks/*
- Rooms: /rooms/*
- Games: /games/*
- Admin: /admin/*
- MTG Cards: /api/cards/*
- Card Interactions: /interactions/*
"""
import logging
from contextlib import asynccontextmanager
from typing import AsyncGenerator
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.core.settings import get_settings
from app.core.database import engine, mtg_engine, async_session, mtg_async_session
from app.routers import auth, users, decks, rooms, games, admin, card_router, interactions
def setup_logging(debug: bool = False) -> None:
"""Configure application logging with verbose support."""
level = logging.DEBUG if debug else logging.INFO
logging.basicConfig(
level=level,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(),
]
)
if debug:
logging.getLogger('sqlalchemy.engine').setLevel(logging.WARNING)
logging.getLogger('sqlalchemy.pool').setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
logger.info(f"Logging initialized at level {logging.getLevelName(level)}")
def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
"""Application lifespan events for startup and shutdown."""
settings = get_settings()
# Startup
setup_logging(debug=settings.DEBUG)
logger = logging.getLogger(__name__)
logger.info(f"MTG Online Backend starting (v{settings.APP_VERSION})")
logger.info(f"Database: {settings.DATABASE_URL.split('@')[1] if '@' in settings.DATABASE_URL else 'configured'}")
logger.info(f"MTG Database: {settings.MTG_DATABASE_URL.split('@')[1] if '@' in settings.MTG_DATABASE_URL else 'configured'}")
logger.info(f"Redis: {settings.REDIS_URL}")
yield
# Shutdown
logger.info("Shutting down MTG Online Backend")
# Engine disposal is handled by FastAPI's shutdown events
app = FastAPI(
title="MTG Online Backend API",
description="Backend API for the MTG Online multiplayer platform",
version="0.2.0",
lifespan=lifespan,
)
# CORS middleware
settings = get_settings()
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Mount all routers
app.include_router(auth.router, prefix="/auth", tags=["Authentication"])
app.include_router(users.router, prefix="/users", tags=["Users"])
app.include_router(decks.router, prefix="/decks", tags=["Decks"])
app.include_router(rooms.router, prefix="/rooms", tags=["Rooms"])
app.include_router(games.router, prefix="/games", tags=["Games"])
app.include_router(admin.router, prefix="/admin", tags=["Admin"])
app.include_router(card_router.router, prefix="/api", tags=["MTG Cards"])
app.include_router(interactions.router, tags=["Card Interactions"])
@app.get("/health", tags=["Health"])
async def health_check():
"""Health check endpoint."""
return {
"status": "healthy",
"version": settings.APP_VERSION,
}
@app.get("/", tags=["Root"])
async def root():
"""Root endpoint with API information."""
return {
"name": settings.APP_NAME,
"version": settings.APP_VERSION,
"docs": "/docs",
}