Create main.py
Browse files- app/main.py +68 -0
app/main.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
from fastapi import FastAPI, Request, HTTPException
|
3 |
+
from fastapi.responses import FileResponse, JSONResponse
|
4 |
+
from fastapi.staticfiles import StaticFiles
|
5 |
+
from fastapi.middleware.cors import CORSMiddleware # Optional: If needed later
|
6 |
+
|
7 |
+
# Import the data loading function from data.py
|
8 |
+
from .data import get_sorted_leaderboard_data
|
9 |
+
|
10 |
+
# Configure logging
|
11 |
+
logging.basicConfig(level=logging.INFO)
|
12 |
+
logger = logging.getLogger(__name__)
|
13 |
+
|
14 |
+
app = FastAPI(title="Leaderboard API")
|
15 |
+
|
16 |
+
try:
|
17 |
+
app.mount("/static", StaticFiles(directory="static"), name="static")
|
18 |
+
except RuntimeError:
|
19 |
+
logger.warning("Static directory not found or is invalid. Static files (CSS, JS) may not be served.")
|
20 |
+
|
21 |
+
|
22 |
+
@app.get("/", include_in_schema=False)
|
23 |
+
async def read_index():
|
24 |
+
"""Serves the main index.html file."""
|
25 |
+
logger.info("Serving index.html")
|
26 |
+
# Ensure index.html exists at the root level alongside the 'app' folder
|
27 |
+
try:
|
28 |
+
return FileResponse('index.html', media_type='text/html')
|
29 |
+
except RuntimeError as e:
|
30 |
+
logger.error(f"Error serving index.html: {e}. Make sure index.html exists in the root directory.")
|
31 |
+
raise HTTPException(status_code=500, detail="Frontend file not found.")
|
32 |
+
|
33 |
+
|
34 |
+
@app.get("/api/leaderboard")
|
35 |
+
async def get_leaderboard():
|
36 |
+
"""Returns the sorted leaderboard data."""
|
37 |
+
logger.info("Request received for /api/leaderboard")
|
38 |
+
try:
|
39 |
+
data = get_sorted_leaderboard_data()
|
40 |
+
return JSONResponse(content=data)
|
41 |
+
except HTTPException as http_exc:
|
42 |
+
# Forward HTTPException raised by data loading function
|
43 |
+
logger.error(f"HTTPException during data retrieval: {http_exc.detail}")
|
44 |
+
raise http_exc
|
45 |
+
except Exception as e:
|
46 |
+
# Catch any other unexpected errors during data retrieval
|
47 |
+
logger.error(f"Unexpected error getting leaderboard data: {e}", exc_info=True)
|
48 |
+
raise HTTPException(status_code=500, detail="An internal error occurred while retrieving leaderboard data.")
|
49 |
+
|
50 |
+
|
51 |
+
# Health check endpoint (optional but good practice)
|
52 |
+
@app.get("/health")
|
53 |
+
async def health_check():
|
54 |
+
return {"status": "ok"}
|
55 |
+
|
56 |
+
# Example of adding a custom exception handler (optional)
|
57 |
+
@app.exception_handler(Exception)
|
58 |
+
async def general_exception_handler(request: Request, exc: Exception):
|
59 |
+
logger.error(f"Unhandled exception for request {request.url}: {exc}", exc_info=True)
|
60 |
+
return JSONResponse(
|
61 |
+
status_code=500,
|
62 |
+
content={"message": "An internal server error occurred."},
|
63 |
+
)
|
64 |
+
|
65 |
+
if __name__ == "__main__":
|
66 |
+
# This block is mainly for local development, uvicorn command is used in Docker
|
67 |
+
import uvicorn
|
68 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|