- 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
50 lines
1.6 KiB
Python
50 lines
1.6 KiB
Python
"""Shared building blocks of the source parsers."""
|
|
|
|
from collections.abc import Callable
|
|
from dataclasses import dataclass
|
|
from typing import Any
|
|
from zoneinfo import ZoneInfo
|
|
|
|
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
|
|
|
|
|
|
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",
|
|
)
|