Files
aoc/backend/main.py
2025-11-29 09:48:50 +01:00

51 lines
1.4 KiB
Python

import asyncio
import logging
from pathlib import Path
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from routes.fetch import router as fetch_router, run_fetch
from routes.events import router as events_router
from config import ENABLE_PERIODIC_FETCH, FETCH_INTERVAL_MINUTES
app = FastAPI()
app.include_router(fetch_router, prefix="/api")
app.include_router(events_router, prefix="/api")
# Serve a minimal frontend for browsing events. Use an absolute path so it
# works regardless of the working directory used to start uvicorn.
frontend_dir = Path(__file__).parent / "frontend"
app.mount("/", StaticFiles(directory=frontend_dir, html=True), name="frontend")
logger = logging.getLogger("aoc.fetcher")
async def _periodic_fetch():
while True:
try:
await asyncio.to_thread(run_fetch)
logger.info("Periodic fetch completed.")
except Exception as exc:
logger.error("Periodic fetch failed: %s", exc)
await asyncio.sleep(FETCH_INTERVAL_MINUTES * 60)
@app.on_event("startup")
async def start_periodic_fetch():
if ENABLE_PERIODIC_FETCH:
app.state.fetch_task = asyncio.create_task(_periodic_fetch())
@app.on_event("shutdown")
async def stop_periodic_fetch():
task = getattr(app.state, "fetch_task", None)
if task:
task.cancel()
try:
await task
except Exception:
pass