Price not found exception handler

This commit is contained in:
Adam Štrauch 2024-08-08 10:40:54 +02:00
parent 0e2ce322c0
commit 5c12390c73
Signed by: cx
GPG Key ID: 7262DAFE292BCE20
2 changed files with 12 additions and 5 deletions

View File

@ -2,10 +2,10 @@ import datetime
import calendar import calendar
from typing import List from typing import List
from fastapi import FastAPI from fastapi import FastAPI, HTTPException
from fastapi.responses import RedirectResponse 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 calculator.schema import CheapestHours, DayPrice, Price
from .consts import VAT from .consts import VAT
@ -92,7 +92,10 @@ def read_item(
spot_hours = {} spot_hours = {}
spot_hours_for_sell = {} spot_hours_for_sell = {}
spot_hours_total = {} spot_hours_total = {}
try:
spot_data = get_energy_prices(date, no_cache=no_cache) 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(): for key, value in spot_data.items():
kwh_fees = kwh_fees_low if int(key) in low_tariff_hours_parsed else kwh_fees_high kwh_fees = kwh_fees_low if int(key) in low_tariff_hours_parsed else kwh_fees_high

View File

@ -8,6 +8,7 @@ import requests
class PriceException(Exception): pass 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={}" 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: if not hours or no_cache:
r = requests.get(url_energy.format(date_str)) r = requests.get(url_energy.format(date_str))
try:
for raw in r.json()["data"]["dataLine"][1]["point"]: for raw in r.json()["data"]["dataLine"][1]["point"]:
hours[str(int(raw["x"])-1)] = raw["y"] hours[str(int(raw["x"])-1)] = raw["y"]
except IndexError:
raise PriceNotFound()
with open(cache_file, "w") as f: with open(cache_file, "w") as f:
f.write(json.dumps(hours)) f.write(json.dumps(hours))