Files
exchange-rates/app/refresh.py
T
JiriUhlir e39f52f027 Dalsi banky, prehled ve Swaggeru, /status a prazdne promenne
- zdroje rb, unicredit a air
- nahore ve Swaggeru prehled nabizenych a nenabizenych bank s duvody
- GET /status s prehledem vypadku stahovani u jednotlivych bank
- prazdna promenna prostredi znamena vychozi hodnotu
- popis stahovani v documentation/stahovani.md
2026-11-04 15:33:21 +01:00

83 lines
2.7 KiB
Python

"""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.status import RefreshAttempt, RefreshHistory
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 _download(client: httpx.AsyncClient, source: Source) -> str:
if source.fetch is not None:
return await source.fetch(client)
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()
return response.text
async def refresh_source(client: httpx.AsyncClient, source: Source, data_dir: Path) -> None:
parsed = source.parse(await _download(client, source))
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))
def _describe_error(error: Exception) -> str:
"""Only the first line, the full detail with a traceback goes to the log."""
message = str(error).splitlines()[0] if str(error) else ""
return f"{type(error).__name__}: {message}"
async def refresh_all(
client: httpx.AsyncClient,
data_dir: Path,
history: RefreshHistory,
) -> None:
"""A failed source keeps its last good file and does not affect the others."""
for source in SOURCES.values():
error = None
try:
await refresh_source(client, source, data_dir)
except Exception as caught:
logger.exception("Refresh of source %s failed, keeping the last stored data", source.id)
error = _describe_error(caught)
history[source.id] = RefreshAttempt(attempted_at=datetime.now(UTC), error=error)
async def refresh_forever(
data_dir: Path,
interval_minutes: int,
history: RefreshHistory,
) -> 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, history)
await asyncio.sleep(interval_minutes * 60)