From 5c12390c73096f88aa13c80ff72b3119403a0f30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20=C5=A0trauch?= Date: Thu, 8 Aug 2024 10:40:54 +0200 Subject: [PATCH] Price not found exception handler --- calculator/main.py | 9 ++++++--- calculator/miner.py | 8 ++++++-- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/calculator/main.py b/calculator/main.py index 840bd2f..4423cd9 100644 --- a/calculator/main.py +++ b/calculator/main.py @@ -2,10 +2,10 @@ import datetime import calendar from typing import List -from fastapi import FastAPI +from fastapi import FastAPI, HTTPException from fastapi.responses import RedirectResponse -from calculator.miner import get_energy_prices, get_eur_czk_ratio +from calculator.miner import PriceNotFound, get_energy_prices, get_eur_czk_ratio from calculator.schema import CheapestHours, DayPrice, Price from .consts import VAT @@ -92,7 +92,10 @@ def read_item( spot_hours = {} spot_hours_for_sell = {} spot_hours_total = {} - spot_data = get_energy_prices(date, no_cache=no_cache) + try: + spot_data = get_energy_prices(date, no_cache=no_cache) + except PriceNotFound: + raise HTTPException(status_code=404, detail="prices not found") for key, value in spot_data.items(): kwh_fees = kwh_fees_low if int(key) in low_tariff_hours_parsed else kwh_fees_high diff --git a/calculator/miner.py b/calculator/miner.py index b94dec6..b3bd988 100644 --- a/calculator/miner.py +++ b/calculator/miner.py @@ -8,6 +8,7 @@ import requests class PriceException(Exception): pass +class PriceNotFound(Exception): pass url_energy = "https://www.ote-cr.cz/cs/kratkodobe-trhy/elektrina/denni-trh/@@chart-data?report_date={}" @@ -33,8 +34,11 @@ def get_energy_prices(d: datetime.date=datetime.date.today(), no_cache:bool=Fals if not hours or no_cache: r = requests.get(url_energy.format(date_str)) - for raw in r.json()["data"]["dataLine"][1]["point"]: - hours[str(int(raw["x"])-1)] = raw["y"] + try: + for raw in r.json()["data"]["dataLine"][1]["point"]: + hours[str(int(raw["x"])-1)] = raw["y"] + except IndexError: + raise PriceNotFound() with open(cache_file, "w") as f: f.write(json.dumps(hours))