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
This commit is contained in:
JiriUhlir
2026-11-04 15:33:21 +01:00
parent 4c81c5bb34
commit e39f52f027
21 changed files with 835 additions and 82 deletions
+27
View File
@@ -0,0 +1,27 @@
"""Text at the top of the Swagger documentation, generated so it cannot drift from the registry."""
from app.sources import SOURCES, UNAVAILABLE_SOURCES
def build_description() -> str:
offered = "\n".join(
f"| `/{source.id}` | {source.name} | {source.note or ''} |" for source in SOURCES.values()
)
not_offered = "\n".join(f"| {item.name} | {item.reason} |" for item in UNAVAILABLE_SOURCES)
return f"""Kurzy měn z ČNB a českých bank ve stejném tvaru pro všechny zdroje.
Aplikace při přechodu na jinou banku mění jen cestu.
## Nabízené banky
| Cesta | Banka | Poznámka |
| --- | --- | --- |
{offered}
## Nenabízené banky
| Banka | Proč |
| --- | --- |
{not_offered}
Přehled není úplný výčet všech bank v ČR.
"""
+15 -5
View File
@@ -4,6 +4,9 @@ import os
from dataclasses import dataclass
from pathlib import Path
DEFAULT_APP_NAME = "Exchange rates"
DEFAULT_APP_VERSION = "1.0.0"
DEFAULT_DATA_DIR = "data"
DEFAULT_REFRESH_INTERVAL_MINUTES = 60
@@ -16,8 +19,15 @@ class Settings:
refresh_interval_minutes: int
def _env_or_default(name: str, default: str) -> str:
"""A variable left empty in the portal means the same as a variable that is not set."""
return os.getenv(name, "").strip() or default
def load_settings() -> Settings:
raw_interval = os.getenv("REFRESH_INTERVAL_MINUTES", str(DEFAULT_REFRESH_INTERVAL_MINUTES))
raw_interval = _env_or_default(
"REFRESH_INTERVAL_MINUTES", str(DEFAULT_REFRESH_INTERVAL_MINUTES)
)
try:
interval = int(raw_interval)
except ValueError as error:
@@ -26,9 +36,9 @@ def load_settings() -> Settings:
raise ValueError(f"REFRESH_INTERVAL_MINUTES must be positive, got {interval}")
return Settings(
app_name=os.getenv("APP_NAME", "Exchange rates"),
app_version=os.getenv("APP_VERSION", "1.0.0"),
root_path=os.getenv("ROOT_PATH", ""),
data_dir=Path(os.getenv("DATA_DIR", "data")),
app_name=_env_or_default("APP_NAME", DEFAULT_APP_NAME),
app_version=_env_or_default("APP_VERSION", DEFAULT_APP_VERSION),
root_path=_env_or_default("ROOT_PATH", ""),
data_dir=Path(_env_or_default("DATA_DIR", DEFAULT_DATA_DIR)),
refresh_interval_minutes=interval,
)
+20 -8
View File
@@ -2,30 +2,31 @@ import asyncio
import logging
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager, suppress
from datetime import UTC, datetime, timedelta
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")
# 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()
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))
task = asyncio.create_task(
refresh_forever(settings.data_dir, settings.refresh_interval_minutes, refresh_history)
)
yield
task.cancel()
with suppress(asyncio.CancelledError):
@@ -35,11 +36,13 @@ async def lifespan(_: FastAPI) -> AsyncIterator[None]:
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"}
@@ -55,6 +58,16 @@ def version() -> dict[str, str]:
}
@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}",
@@ -87,10 +100,9 @@ def get_rates(
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,
stale=is_stale(sheet.fetched_at, datetime.now(UTC), settings.refresh_interval_minutes),
)
+30 -6
View File
@@ -10,6 +10,7 @@ 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__)
@@ -19,13 +20,19 @@ 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:
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()
parsed = source.parse(response.text)
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,
@@ -38,21 +45,38 @@ async def refresh_source(client: httpx.AsyncClient, source: Source, data_dir: Pa
logger.info("Refreshed source %s with %d rates", source.id, len(sheet.rates))
async def refresh_all(client: httpx.AsyncClient, data_dir: Path) -> None:
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:
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) -> None:
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)
await refresh_all(client, data_dir, history)
await asyncio.sleep(interval_minutes * 60)
+113 -38
View File
@@ -1,8 +1,26 @@
"""Registry of the supported sources. The key is the public URL segment."""
"""Registry of the sources. The key of SOURCES is the public URL segment."""
from app.sources import cnb, creditas, csob, fio, jt, kb, mbank, moneta, ppf, trinity
from dataclasses import dataclass
from app.sources import (
air,
cnb,
creditas,
csob,
fio,
jt,
kb,
mbank,
moneta,
ppf,
rb,
trinity,
unicredit,
)
from app.sources.base import Source
UNSPECIFIED_RATE_NOTE = "Stránka banky neuvádí, jestli jde o bezhotovostní kurz."
SOURCES: dict[str, Source] = {
source.id: source
for source in (
@@ -14,6 +32,7 @@ SOURCES: dict[str, Source] = {
"kurzy-devizoveho-trhu/denni_kurz.txt"
),
parse=cnb.parse,
note="Vyhlašuje jeden kurz, takže buy, sell a middle jsou stejné.",
),
Source(
id="kb",
@@ -21,42 +40,6 @@ SOURCES: dict[str, Source] = {
url="https://www.kb.cz/cs/kurzovni-listek",
parse=kb.parse,
),
Source(
id="jt",
name="J&T Banka",
url="https://www.jtbank.cz/kurzovni-listek",
parse=jt.parse,
),
Source(
id="mbank",
name="mBank",
url="https://www.mbank.cz/kurzovni-listek/",
parse=mbank.parse,
),
Source(
id="ppf",
name="PPF banka",
url="https://www.ppfbanka.cz/cs/kurzovni-listek",
parse=ppf.parse,
),
Source(
id="trinity",
name="Trinity Bank",
url="https://public.trinitybank.cz/cs/kurzovni-listek",
parse=trinity.parse,
),
Source(
id="fio",
name="Fio banka",
url="https://www.fio.cz/akcie-investice/dalsi-sluzby-fio/devizove-konverze",
parse=fio.parse,
),
Source(
id="creditas",
name="Banka CREDITAS",
url="https://www.creditas.cz/kurzovni-listek",
parse=creditas.parse,
),
Source(
id="csob",
name="ČSOB",
@@ -70,5 +53,97 @@ SOURCES: dict[str, Source] = {
parse=moneta.parse,
request_json={},
),
Source(
id="rb",
name="Raiffeisenbank",
url="https://www.rb.cz/frontend-controller/backend-data/currency/listActual",
parse=rb.parse,
),
Source(
id="unicredit",
name="UniCredit Bank",
url=unicredit.URL,
parse=unicredit.parse,
fetch=unicredit.fetch,
),
Source(
id="air",
name="Air Bank",
url="https://www.airbank.cz/graphql",
parse=air.parse,
request_json={"query": air.QUERY},
note="Datum platnosti je datum poslední revize lístku, může být z předchozího dne.",
),
Source(
id="fio",
name="Fio banka",
url="https://www.fio.cz/akcie-investice/dalsi-sluzby-fio/devizove-konverze",
parse=fio.parse,
),
Source(
id="jt",
name="J&T Banka",
url="https://www.jtbank.cz/kurzovni-listek",
parse=jt.parse,
),
Source(
id="mbank",
name="mBank",
url="https://www.mbank.cz/kurzovni-listek/",
parse=mbank.parse,
note=UNSPECIFIED_RATE_NOTE,
),
Source(
id="ppf",
name="PPF banka",
url="https://www.ppfbanka.cz/cs/kurzovni-listek",
parse=ppf.parse,
note=UNSPECIFIED_RATE_NOTE,
),
Source(
id="trinity",
name="Trinity Bank",
url="https://public.trinitybank.cz/cs/kurzovni-listek",
parse=trinity.parse,
),
Source(
id="creditas",
name="Banka CREDITAS",
url="https://www.creditas.cz/kurzovni-listek",
parse=creditas.parse,
note=(
"Nespolehlivé: server banky stahování často odmítá (403), odpověď pak může být 503. "
"Banka kurzy označuje jako orientační."
),
),
)
}
@dataclass(frozen=True)
class UnavailableSource:
name: str
reason: str
UNAVAILABLE_SOURCES: tuple[UnavailableSource, ...] = (
UnavailableSource(
name="Česká spořitelna",
reason="Kurzy jsou dostupné jen přes API s klíčem. Vlastní klíč zatím nemáme.",
),
UnavailableSource(
name="Revolut",
reason=(
"Nemá veřejný kurzovní lístek a web strojový přístup k API zakazuje. "
"Oficiální cesta je Business API s tokenem, který zatím nemáme."
),
),
UnavailableSource(
name="Partners Banka",
reason="Kurzovní lístek jsme nenašli, web popisuje jen kartové platby kurzem ECB.",
),
UnavailableSource(
name="Oberbank",
reason="Veřejný kurzovní lístek jsme na webu nenašli.",
),
)
+32
View File
@@ -0,0 +1,32 @@
"""Air Bank: the GraphQL endpoint used by the bank's own rate list page."""
import json
from datetime import date
from app.models import ParsedRates
from app.sources.base import make_rate
QUERY = "{ exchangeRates { rates { code buy sell quantity lastRevisionDate } } }"
ISO_DATE_LENGTH = 10
def parse(document: str) -> ParsedRates:
items = json.loads(document)["data"]["exchangeRates"]["rates"]
# The source has no validity date, only a revision date that some currencies leave empty.
# The list is valid since its latest revision, which can be the previous day.
revisions = [item["lastRevisionDate"] for item in items if item["lastRevisionDate"]]
if not revisions:
raise ValueError("Air Bank revision date not found")
rates = [
make_rate(
currency=item["code"],
amount=item["quantity"],
buy=item["buy"],
sell=item["sell"],
)
for item in items
if item["buy"] and item["sell"]
]
return ParsedRates(valid_date=date.fromisoformat(max(revisions)[:ISO_DATE_LENGTH]), rates=rates)
+7 -1
View File
@@ -1,10 +1,12 @@
"""Shared building blocks of the source parsers."""
from collections.abc import Callable
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import Any
from zoneinfo import ZoneInfo
import httpx
from app.models import Origin, ParsedRates, Rate
# Dividing by the quoted amount (for example 100 JPY) must not lose precision
@@ -23,6 +25,10 @@ class Source:
parse: Callable[[str], ParsedRates]
# When set, the source is requested with POST and this JSON body instead of GET.
request_json: dict[str, Any] | None = None
# When set, replaces the single request, for sources that need several of them.
fetch: Callable[[httpx.AsyncClient], Awaitable[str]] | None = None
# Shown in the API documentation when consumers should know something about the source.
note: str | None = None
def parse_comma_decimal(value: str) -> float:
+31
View File
@@ -0,0 +1,31 @@
"""Raiffeisenbank: the JSON endpoint used by the bank's own rate list page."""
import json
from datetime import datetime
from app.models import ParsedRates
from app.sources.base import PRAGUE_ZONE, make_rate
def parse(document: str) -> ParsedRates:
# The bank publishes several lists a day, only the last one is currently valid.
rate_lists = json.loads(document)["exchangeRateLists"]
current = next((item for item in rate_lists if item["lastRates"]), None)
if current is None:
raise ValueError("Raiffeisenbank current rate list not found")
# exchangeRateBuy and exchangeRateSell are non-cash, the cash rates have a Cash suffix.
rates = [
make_rate(
currency=item["currencyFrom"],
amount=item["unitsFrom"],
buy=item["exchangeRateBuy"],
sell=item["exchangeRateSell"],
middle=item["exchangeRateCenter"],
)
for item in current["exchangeRates"]
if item["exchangeRateBuy"] and item["exchangeRateSell"]
]
valid_from = datetime.fromisoformat(current["effectiveDateFrom"])
return ParsedRates(valid_date=valid_from.astimezone(PRAGUE_ZONE).date(), rates=rates)
+88
View File
@@ -0,0 +1,88 @@
"""UniCredit Bank: the JSON endpoint used by the bank's own page, one request per currency."""
import json
from datetime import datetime
import httpx
from app.models import ParsedRates
from app.sources.base import PRAGUE_ZONE, make_rate
URL = "https://www.unicreditbank.cz/cwa/GetExchangeRates"
# Headers and date format are what the bank's page sends, the endpoint rejects anything else.
REQUEST_HEADERS = {
"EntityCode": "CZ",
"UserID": "",
"Language": "CS",
"SourceSystem": "PWS",
"Product": "PWS",
}
REQUEST_DATE_FORMAT = "%Y%m%dT%H:%M:%S.000%z"
# Currencies listed on the bank's page with the units the prices refer to. The API does not
# return the units, its page keeps them in the jsonCurrencyAmounts variable.
CURRENCY_UNITS = {
"AUD": 1,
"BAM": 1,
"CAD": 1,
"CHF": 1,
"CNY": 1,
"DKK": 1,
"EUR": 1,
"GBP": 1,
"HKD": 1,
"HUF": 100,
"JPY": 100,
"NOK": 1,
"NZD": 1,
"PLN": 1,
"RON": 1,
"RSD": 100,
"SEK": 1,
"SGD": 1,
"TRY": 1,
"USD": 1,
}
async def fetch(client: httpx.AsyncClient) -> str:
"""Any failed currency fails the source, so a partial list never replaces a complete one."""
request_date = datetime.now(PRAGUE_ZONE).strftime(REQUEST_DATE_FORMAT)
items = []
for currency in CURRENCY_UNITS:
response = await client.post(
URL,
headers=REQUEST_HEADERS,
json={
"Currency": currency,
"DateFrom": request_date,
"DateTo": request_date,
"multiplier": "0",
},
)
response.raise_for_status()
items += response.json()
return json.dumps(items)
def parse(document: str) -> ParsedRates:
items = json.loads(document)
if not items:
raise ValueError("UniCredit rate list is empty")
# "Cards" is the non-cash rate, the page shows it in the Devizy tab. "Cash" is in Valuty.
# MiddleRate is the CNB rate, so the middle of the non-cash prices is used instead.
rates = [
make_rate(
currency=item["CurrencyCode"],
amount=CURRENCY_UNITS[item["CurrencyCode"]],
buy=item["CardsPurchaseRate"],
sell=item["CardsSaleRate"],
middle=item["CardsMiddleRate"],
)
for item in items
if item["CardsPurchaseRate"] and item["CardsSaleRate"]
]
latest_update = max(item["ExchangeRateUpdatedTimestamp"] for item in items)
valid_from = datetime.fromisoformat(latest_update)
return ParsedRates(valid_date=valid_from.astimezone(PRAGUE_ZONE).date(), rates=rates)
+93
View File
@@ -0,0 +1,93 @@
"""Tells whether the sources are being refreshed successfully."""
from dataclasses import dataclass
from datetime import datetime, timedelta
from pathlib import Path
from typing import Literal
from pydantic import BaseModel, Field
from app.sources import SOURCES
from app.storage import read_sheet
# 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
SourceState = Literal["ok", "failing", "pending"]
@dataclass(frozen=True)
class RefreshAttempt:
attempted_at: datetime
error: str | None
# Kept in memory on purpose: every start refreshes all sources right away, so the
# history is complete again within seconds and there is nothing worth persisting.
RefreshHistory = dict[str, RefreshAttempt]
class SourceStatus(BaseModel):
source: str
source_name: str
state: SourceState = Field(
description="ok: last download succeeded, failing: last download failed, "
"pending: no download attempted since the start"
)
stale: bool = Field(description="True when the stored data may be outdated")
last_success_at: datetime | None = Field(description="Time of the stored data, null if none")
last_attempt_at: datetime | None
last_error: str | None = Field(description="Error of the last attempt, null if it succeeded")
class ServiceStatus(BaseModel):
status: Literal["ok", "degraded"] = Field(description="ok only when all sources are ok")
problems: list[str] = Field(description="Identifiers of the sources that are not ok")
refresh_interval_minutes: int
sources: list[SourceStatus]
def is_stale(fetched_at: datetime, now: datetime, interval_minutes: int) -> bool:
return now - fetched_at > timedelta(minutes=interval_minutes * STALE_AFTER_REFRESH_INTERVALS)
def _source_status(
source_id: str,
attempt: RefreshAttempt | None,
data_dir: Path,
now: datetime,
interval_minutes: int,
) -> SourceStatus:
sheet = read_sheet(data_dir, source_id)
state: SourceState = "pending"
if attempt is not None:
state = "ok" if attempt.error is None else "failing"
return SourceStatus(
source=source_id,
source_name=SOURCES[source_id].name,
state=state,
stale=sheet is None or is_stale(sheet.fetched_at, now, interval_minutes),
last_success_at=sheet.fetched_at if sheet else None,
last_attempt_at=attempt.attempted_at if attempt else None,
last_error=attempt.error if attempt else None,
)
def build_status(
history: RefreshHistory,
data_dir: Path,
now: datetime,
interval_minutes: int,
) -> ServiceStatus:
sources = [
_source_status(source_id, history.get(source_id), data_dir, now, interval_minutes)
for source_id in SOURCES
]
problems = [item.source for item in sources if item.state != "ok"]
return ServiceStatus(
status="degraded" if problems else "ok",
problems=problems,
refresh_interval_minutes=interval_minutes,
sources=sources,
)