Use cached FX rate if fresh rate not available

This commit is contained in:
Edward Betts 2024-05-01 08:31:14 +02:00
parent 2b822e28a0
commit a5d1290491

View file

@ -44,6 +44,17 @@ async def get_gbpusd(config: flask.config.Config) -> Decimal:
return typing.cast(Decimal, 1 / data["quotes"]["USDGBP"]) return typing.cast(Decimal, 1 / data["quotes"]["USDGBP"])
def read_cached_rates(filename: str, currencies: list[str]) -> dict[str, Decimal]:
"""Read FX rates from cache."""
with open(filename) as file:
data = json.load(file, parse_float=Decimal)
return {
cur: Decimal(data["quotes"][f"GBP{cur}"])
for cur in currencies
if f"GBP{cur}" in data["quotes"]
}
def get_rates(config: flask.config.Config) -> dict[str, Decimal]: def get_rates(config: flask.config.Config) -> dict[str, Decimal]:
"""Get current values of exchange rates for a list of currencies against GBP.""" """Get current values of exchange rates for a list of currencies against GBP."""
currencies = config["CURRENCIES"] currencies = config["CURRENCIES"]
@ -65,22 +76,19 @@ def get_rates(config: flask.config.Config) -> dict[str, Decimal]:
recent = datetime.strptime(recent_filename[:16], "%Y-%m-%d_%H:%M") recent = datetime.strptime(recent_filename[:16], "%Y-%m-%d_%H:%M")
delta = now - recent delta = now - recent
if delta < timedelta(hours=12):
full_path = os.path.join(fx_dir, recent_filename) full_path = os.path.join(fx_dir, recent_filename)
with open(full_path) as file: if delta < timedelta(hours=12):
data = json.load(file, parse_float=Decimal) return read_cached_rates(full_path, currencies)
return {
cur: Decimal(data["quotes"][f"GBP{cur}"])
for cur in currencies
if f"GBP{cur}" in data["quotes"]
}
url = "http://api.exchangerate.host/live" url = "http://api.exchangerate.host/live"
params = {"currencies": currency_string, "source": "GBP", "access_key": access_key} params = {"currencies": currency_string, "source": "GBP", "access_key": access_key}
filename = f"{now_str}_{file_suffix}" filename = f"{now_str}_{file_suffix}"
try:
with httpx.Client() as client: with httpx.Client() as client:
response = client.get(url, params=params) response = client.get(url, params=params)
except httpx.ConnectError:
return read_cached_rates(full_path, currencies)
with open(os.path.join(fx_dir, filename), "w") as file: with open(os.path.join(fx_dir, filename), "w") as file:
file.write(response.text) file.write(response.text)