Files
mcp-moex/cbrcurrency.py

32 lines
995 B
Python

from cachetools import TTLCache
import json
from session import session
__CBR_DAYLY_URL = "https://www.cbr-xml-daily.ru/daily_json.js"
__cache: TTLCache = TTLCache(maxsize=10000, ttl=60 * 10)
def __fetch_currency() -> dict:
if __CBR_DAYLY_URL in __cache:
return __cache[__CBR_DAYLY_URL]
resp = session.get(__CBR_DAYLY_URL)
data = resp.json()
__cache[__CBR_DAYLY_URL] = data["Valute"]
return data["Valute"]
def get_currency(currency_charcode: str) -> dict:
if not currency_charcode in __cache:
currencies = __fetch_currency()
if currency_charcode in currencies:
currency = currencies[currency_charcode]
nominal = int(currency["Nominal"])
value = float(currency["Value"])
return {f"1_{currency_charcode}": value / nominal, "CharCode": currency_charcode, "Name": currency["Name"]}
else:
return {"error": f'Unknow currency charcode {currency_charcode}'}