Files
mtgonline/backend/app/main.py
T
akadmin 1331885455 Fix critical bug and deprecation warnings
- Fixed bug in games_router.py: player_result -> player_stmt in create_game
- Updated main.py lifespan from generator to @asynccontextmanager (FastAPI deprecation)
- security.py already uses datetime.now(timezone.utc) - no change needed
- All 28 tests pass
2026-10-19 06:33:28 +00:00

116 lines
3.5 KiB
Python

"""
MTG Online Backend Application
FastAPI application for the MTG Online multiplayer platform.
Mounts all consolidated routers and provides centralized configuration.
## Routers (Consolidated Structure)
- Authentication: /auth/*
- Users + Admin: /users/*
- Decks: /decks/*
- Cards + Interactions: /api/cards/*, /interactions/*
- User Data + Imports: /api/v1/user-data/*, /api/v1/card-import/*
- Games + Rooms + Refresh: /games/*, /rooms/*, /mtgjson/*
- WebSocket: /ws/game/{game_id}
"""
import asyncio
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy import text
from app.core.config import get_config
from app.core.database import engine, get_db
from app.routers import (
auth_router,
users_router,
decks_router,
cards_router,
user_data_router,
games_router,
)
from app.core.logging import configure_logging
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Application lifespan events for startup and shutdown."""
config = get_config()
# Configure logging
configure_logging()
logger.info(f"MTG Online Backend starting (v{config.APP_VERSION})")
logger.info(f"Database: {config.DATABASE_URL}")
logger.info(f"Environment: {'development' if config.DEBUG else 'production'}")
yield
# Shutdown
logger.info("Shutting down MTG Online Backend")
app = FastAPI(
title="MTG Online Backend API",
description="Backend API for the MTG Online multiplayer platform",
version="0.3.0",
lifespan=lifespan,
)
# CORS middleware
config = get_config()
app.add_middleware(
CORSMiddleware,
allow_origins=config.CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Mount all consolidated routers
app.include_router(auth_router.router, prefix="/auth", tags=["Authentication"])
app.include_router(users_router.router, prefix="/users", tags=["Users", "Admin"])
app.include_router(decks_router.router, prefix="/decks", tags=["Decks"])
app.include_router(cards_router.card_router, tags=["MTG Cards"])
app.include_router(cards_router.interaction_router, tags=["Card Interactions"])
app.include_router(user_data_router.user_data_router, prefix="/api/v1/user-data", tags=["User Data"])
app.include_router(user_data_router.card_import_router, prefix="/api/v1/card-import", tags=["Card Import"])
app.include_router(games_router.rooms_router, prefix="/rooms", tags=["Rooms"])
app.include_router(games_router.games_router, prefix="/games", tags=["Games"])
app.include_router(games_router.mtgjson_router, prefix="/mtgjson", tags=["MTGJSON"])
app.include_router(games_router.router, tags=["WebSocket"])
@app.get("/health", tags=["Health"])
async def health_check():
"""Health check endpoint with database status."""
health_status = {
"status": "healthy",
"version": config.APP_VERSION,
}
# Check database
try:
async with engine.connect() as conn:
await conn.execute(text("SELECT 1"))
health_status["database"] = "healthy"
except Exception as e:
health_status["database"] = {"status": "unhealthy", "error": str(e)}
health_status["status"] = "unhealthy"
return health_status
@app.get("/", tags=["Root"])
async def root():
"""Root endpoint with API information."""
return {
"name": config.APP_NAME,
"version": config.APP_VERSION,
"docs": "/docs",
}