import asyncio import logging from collections.abc import AsyncIterator from contextlib import asynccontextmanager, suppress from datetime import UTC, datetime from fastapi import FastAPI, HTTPException, Path, Query from app.api_description import build_description from app.config import load_settings from app.conversion import CZK, BaseCurrencyNotAvailable, rebase_rates from app.models import RateSheetResponse from app.refresh import refresh_forever from app.sources import SOURCES from app.status import RefreshHistory, ServiceStatus, build_status, is_stale from app.storage import read_sheet logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") settings = load_settings() refresh_history: RefreshHistory = {} @asynccontextmanager async def lifespan(_: FastAPI) -> AsyncIterator[None]: # Runs in the background, so the health check answers while the first refresh is in progress. task = asyncio.create_task( refresh_forever(settings.data_dir, settings.refresh_interval_minutes, refresh_history) ) yield task.cancel() with suppress(asyncio.CancelledError): await task app = FastAPI( title=settings.app_name, version=settings.app_version, description=build_description(), root_path=settings.root_path, lifespan=lifespan, ) # Stays 200 when a bank is down: the application itself works and a restart would not help. @app.get("/health") def health() -> dict[str, str]: return {"status": "ok"} @app.get("/version") def version() -> dict[str, str]: return { "app": settings.app_name, "version": settings.app_version, "language": "python", "root_path": settings.root_path, } @app.get("/status", description="Výpadky stahování: stav posledního stažení u každé banky.") def status() -> ServiceStatus: return build_status( refresh_history, settings.data_dir, datetime.now(UTC), settings.refresh_interval_minutes, ) # Must stay the last route, otherwise it would capture the static paths above. @app.get( "/{source_id}", response_model=RateSheetResponse, responses={ 404: {"description": "Unknown source, or the source does not publish the base currency"}, 503: {"description": "The source has no stored data yet"}, }, ) def get_rates( source_id: str = Path(description=f"Source identifier: {', '.join(SOURCES)}"), base: str = Query( default=CZK, pattern=r"^[A-Z]{3}$", description="Currency to express the prices in. Other than CZK is computed through CZK.", ), ) -> RateSheetResponse: if source_id not in SOURCES: raise HTTPException(status_code=404, detail=f"Unknown source. Available: {', '.join(SOURCES)}") sheet = read_sheet(settings.data_dir, source_id) if sheet is None: raise HTTPException(status_code=503, detail="No data has been downloaded for this source yet") try: rates = rebase_rates(sheet.rates, base) except BaseCurrencyNotAvailable as error: raise HTTPException( status_code=404, detail=f"Source {source_id} does not publish base currency {base}", ) from error return RateSheetResponse( **sheet.model_dump(exclude={"rates"}), rates=rates, base=base, stale=is_stale(sheet.fetched_at, datetime.now(UTC), settings.refresh_interval_minutes), )