Files
game-marathon/backend/app/main.py

81 lines
2.1 KiB
Python
Raw Normal View History

2025-12-16 22:43:03 +07:00
import logging
2025-12-14 02:38:35 +07:00
from contextlib import asynccontextmanager
2025-12-18 17:15:21 +07:00
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from slowapi import _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
2025-12-16 22:43:03 +07:00
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
2025-12-14 02:38:35 +07:00
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from pathlib import Path
from app.core.config import settings
2025-12-15 03:22:29 +07:00
from app.core.database import engine, Base, async_session_maker
2025-12-18 17:15:21 +07:00
from app.core.rate_limit import limiter
2025-12-14 02:38:35 +07:00
from app.api.v1 import router as api_router
2025-12-15 03:22:29 +07:00
from app.services.event_scheduler import event_scheduler
2025-12-16 00:33:50 +07:00
from app.services.dispute_scheduler import dispute_scheduler
2025-12-14 02:38:35 +07:00
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup: create tables
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
# Create upload directories
upload_dir = Path(settings.UPLOAD_DIR)
(upload_dir / "avatars").mkdir(parents=True, exist_ok=True)
(upload_dir / "covers").mkdir(parents=True, exist_ok=True)
(upload_dir / "proofs").mkdir(parents=True, exist_ok=True)
2025-12-16 00:33:50 +07:00
# Start schedulers
2025-12-15 03:22:29 +07:00
await event_scheduler.start(async_session_maker)
2025-12-16 00:33:50 +07:00
await dispute_scheduler.start(async_session_maker)
2025-12-15 03:22:29 +07:00
2025-12-14 02:38:35 +07:00
yield
# Shutdown
2025-12-15 03:22:29 +07:00
await event_scheduler.stop()
2025-12-16 00:33:50 +07:00
await dispute_scheduler.stop()
2025-12-14 02:38:35 +07:00
await engine.dispose()
app = FastAPI(
title=settings.APP_NAME,
version="1.0.0",
lifespan=lifespan,
)
2025-12-18 17:15:21 +07:00
# Rate limiting
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
2025-12-14 02:38:35 +07:00
# CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000", "http://127.0.0.1:3000"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Static files for uploads
upload_path = Path(settings.UPLOAD_DIR)
if upload_path.exists():
app.mount("/uploads", StaticFiles(directory=str(upload_path)), name="uploads")
# API routes
app.include_router(api_router)
@app.get("/health")
async def health_check():
return {"status": "ok"}