diff --git a/agenda/fx.py b/agenda/fx.py index efd4d7d..0e22711 100644 --- a/agenda/fx.py +++ b/agenda/fx.py @@ -44,10 +44,16 @@ async def get_gbpusd(config: flask.config.Config) -> Decimal: return typing.cast(Decimal, 1 / data["quotes"]["USDGBP"]) -def read_cached_rates(filename: str, currencies: list[str]) -> dict[str, Decimal]: +def read_cached_rates( + filename: str | None, currencies: list[str] +) -> dict[str, Decimal]: """Read FX rates from cache.""" + if filename is None: + return {} + with open(filename) as file: data = json.load(file, parse_float=Decimal) + return { cur: Decimal(data["quotes"][f"GBP{cur}"]) for cur in currencies @@ -69,7 +75,9 @@ def get_rates(config: flask.config.Config) -> dict[str, Decimal]: currency_string = ",".join(sorted(currencies)) file_suffix = f"{currency_string}_to_GBP.json" existing_data = os.listdir(fx_dir) - existing_files = [f for f in existing_data if f.endswith(file_suffix)] + existing_files = [f for f in existing_data if f.endswith(".json")] + + full_path: str | None = None if existing_files: recent_filename = max(existing_files) @@ -77,7 +85,7 @@ def get_rates(config: flask.config.Config) -> dict[str, Decimal]: delta = now - recent full_path = os.path.join(fx_dir, recent_filename) - if delta < timedelta(hours=12): + if not recent_filename.endswith(file_suffix) or delta < timedelta(hours=12): return read_cached_rates(full_path, currencies) url = "http://api.exchangerate.host/live" diff --git a/templates/macros.html b/templates/macros.html index ae77489..a01925b 100644 --- a/templates/macros.html +++ b/templates/macros.html @@ -38,7 +38,7 @@
{% if item.price and item.currency %} {{ "{:,d}".format(item.price | int) }} {{ item.currency }} - {% if item.currency != "GBP" %} + {% if item.currency != "GBP" and item.currency in fx_rate %} {{ "{:,.2f}".format(item.price / fx_rate[item.currency]) }} GBP {% endif %} {% elif item.free %}