Files
exchange-rates/app/sources/base.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

56 lines
1.9 KiB
Python

"""Shared building blocks of the source parsers."""
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
# on small per-unit prices, while float noise from the division is rounded away.
RATE_DECIMALS = 6
# Czech banks state validity in local time, some sources send it as a UTC timestamp.
PRAGUE_ZONE = ZoneInfo("Europe/Prague")
@dataclass(frozen=True)
class Source:
id: str
name: str
url: str
# Pure function of the downloaded document. Raises ValueError when the format changed.
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:
return float(value.replace(",", "."))
def make_rate(
currency: str,
amount: int,
buy: float,
sell: float,
middle: float | None = None,
buy_sell_origin: Origin = "fetched",
) -> Rate:
"""Converts source prices to the universal form: per 1 unit, middle always present."""
quoted_middle = middle if middle is not None else (buy + sell) / 2
return Rate(
currency=currency,
buy=round(buy / amount, RATE_DECIMALS),
sell=round(sell / amount, RATE_DECIMALS),
middle=round(quoted_middle / amount, RATE_DECIMALS),
buy_sell_origin=buy_sell_origin,
middle_origin="fetched" if middle is not None else "computed",
)