Pridani stahovani kurzu a jednotneho API
- GET /{source_id} pro cnb, kb, csob, moneta, jt, mbank, ppf, trinity, fio, creditas
- jednotny tvar odpovedi s bezhotovostnimi kurzy za 1 jednotku meny
- parametr ?base pro ceny v jine mene nez CZK
- pole buy_sell_origin a middle_origin rikaji, co je stazene a co dopocitane
- pravidelne stahovani na pozadi, ukladani do JSON, priznak stale
- testy a dokumentace ve slozce documentation
This commit is contained in:
+84
-13
@@ -1,25 +1,96 @@
|
||||
import os
|
||||
from fastapi import FastAPI
|
||||
import asyncio
|
||||
import logging
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager, suppress
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Path, Query
|
||||
|
||||
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.storage import read_sheet
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
|
||||
# A single missed refresh is normal, for example a short outage on the bank side.
|
||||
# Three missed refreshes in a row mean the consumer should know about it.
|
||||
STALE_AFTER_REFRESH_INTERVALS = 3
|
||||
|
||||
settings = load_settings()
|
||||
|
||||
|
||||
@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))
|
||||
yield
|
||||
task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await task
|
||||
|
||||
APP_NAME = os.getenv("APP_NAME", "Exchange rates")
|
||||
APP_VERSION = os.getenv("APP_VERSION", "1.0.0")
|
||||
ROOT_PATH = os.getenv("ROOT_PATH", "")
|
||||
|
||||
app = FastAPI(
|
||||
title=APP_NAME,
|
||||
version=APP_VERSION,
|
||||
root_path=ROOT_PATH
|
||||
title=settings.app_name,
|
||||
version=settings.app_version,
|
||||
root_path=settings.root_path,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
def health():
|
||||
def health() -> dict[str, str]:
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/version")
|
||||
def version():
|
||||
def version() -> dict[str, str]:
|
||||
return {
|
||||
"app": APP_NAME,
|
||||
"version": APP_VERSION,
|
||||
"app": settings.app_name,
|
||||
"version": settings.app_version,
|
||||
"language": "python",
|
||||
"root_path": ROOT_PATH
|
||||
"root_path": settings.root_path,
|
||||
}
|
||||
|
||||
|
||||
# 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
|
||||
|
||||
max_age = timedelta(minutes=settings.refresh_interval_minutes * STALE_AFTER_REFRESH_INTERVALS)
|
||||
return RateSheetResponse(
|
||||
**sheet.model_dump(exclude={"rates"}),
|
||||
rates=rates,
|
||||
base=base,
|
||||
stale=datetime.now(UTC) - sheet.fetched_at > max_age,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user