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:
JiriUhlir
2026-11-04 15:09:24 +01:00
parent 4e1ac94210
commit 4c81c5bb34
32 changed files with 1446 additions and 16 deletions
+58
View File
@@ -0,0 +1,58 @@
"""Downloads the sources and keeps the stored JSON files up to date."""
import asyncio
import logging
from datetime import UTC, datetime
from pathlib import Path
import httpx
from app.models import RateSheet
from app.sources import SOURCES
from app.sources.base import Source
from app.storage import write_sheet
logger = logging.getLogger(__name__)
# Identifies the service honestly, so a bank can recognise it and decide how to treat it.
USER_AGENT = "exchange-rates-service/1.0"
REQUEST_TIMEOUT_SECONDS = 30.0
async def refresh_source(client: httpx.AsyncClient, source: Source, data_dir: Path) -> None:
if source.request_json is None:
response = await client.get(source.url)
else:
response = await client.post(source.url, json=source.request_json)
response.raise_for_status()
parsed = source.parse(response.text)
sheet = RateSheet(
source=source.id,
source_name=source.name,
source_url=source.url,
fetched_at=datetime.now(UTC),
valid_date=parsed.valid_date,
rates=sorted(parsed.rates, key=lambda rate: rate.currency),
)
write_sheet(data_dir, sheet)
logger.info("Refreshed source %s with %d rates", source.id, len(sheet.rates))
async def refresh_all(client: httpx.AsyncClient, data_dir: Path) -> None:
"""A failed source keeps its last good file and does not affect the others."""
for source in SOURCES.values():
try:
await refresh_source(client, source, data_dir)
except Exception:
logger.exception("Refresh of source %s failed, keeping the last stored data", source.id)
async def refresh_forever(data_dir: Path, interval_minutes: int) -> None:
async with httpx.AsyncClient(
headers={"User-Agent": USER_AGENT},
timeout=REQUEST_TIMEOUT_SECONDS,
follow_redirects=True,
) as client:
while True:
await refresh_all(client, data_dir)
await asyncio.sleep(interval_minutes * 60)