Added option to cache prices
This commit is contained in:
@@ -8,7 +8,7 @@ date_format = "%Y-%m-%dT%H:%M:%S%z"
|
||||
|
||||
|
||||
class EngieAPI:
|
||||
def __init__(self):
|
||||
def __init__(self, cache: bool = False):
|
||||
self.url = "https://benergy-back.azurewebsites.net/api/gateway/mercure"
|
||||
self.headers = {
|
||||
"Host": "benergy-back.azurewebsites.net",
|
||||
@@ -22,7 +22,21 @@ class EngieAPI:
|
||||
"Accept-Language": "en-GB,en;q=0.9",
|
||||
}
|
||||
|
||||
self.cache = cache
|
||||
self.cache_file = "EngieCache.json"
|
||||
|
||||
def get_epex_spot(self, date: date) -> List[float]:
|
||||
if self.cache:
|
||||
try:
|
||||
with open("EngieCache.json", "r") as f:
|
||||
cache = json.load(f)
|
||||
print(cache)
|
||||
except FileNotFoundError:
|
||||
cache = {}
|
||||
|
||||
if date.strftime("%Y-%m-%d") in cache:
|
||||
return cache[date.strftime("%Y-%m-%d")]
|
||||
|
||||
to_date = datetime(date.year, date.month, date.day, 23, 59, 59)
|
||||
from_date = to_date - timedelta(days=1, hours=23, minutes=59, seconds=59)
|
||||
|
||||
@@ -40,10 +54,27 @@ class EngieAPI:
|
||||
|
||||
values = []
|
||||
for j in res.json()[0]["Points"]:
|
||||
print(j)
|
||||
# check if the Date is the same as the one requested, attention to the timezone
|
||||
if datetime.strptime(j["Date"], date_format).date() == date:
|
||||
if datetime.strptime(j["Date"], date_format).date().strftime(
|
||||
"%Y-%m-%d"
|
||||
) == date.strftime("%Y-%m-%d"):
|
||||
values.append(j["Value"])
|
||||
|
||||
if self.cache:
|
||||
# check if the cache exists else create it
|
||||
try:
|
||||
with open("EngieCache.json", "r") as f:
|
||||
cache = json.load(f)
|
||||
except FileNotFoundError:
|
||||
cache = {}
|
||||
|
||||
# update cache
|
||||
cache[date.strftime("%Y-%m-%d")] = values
|
||||
|
||||
with open("EngieCache.json", "w+") as f:
|
||||
json.dump(cache, f)
|
||||
|
||||
if not values:
|
||||
raise ValueError("No data found for this date")
|
||||
return values
|
||||
|
||||
Reference in New Issue
Block a user