Download bank-holidays.json if the local copy is unreadable

This commit is contained in:
Edward Betts 2024-01-08 15:18:28 +00:00
parent 7a5319aa83
commit acbad39df7

View file

@ -8,7 +8,7 @@ from time import time
import httpx
from dateutil.easter import easter
from .types import Holiday
from .types import Holiday, StrDict
async def bank_holiday_list(
@ -17,13 +17,23 @@ async def bank_holiday_list(
"""Date and name of the next UK bank holiday."""
url = "https://www.gov.uk/bank-holidays.json"
filename = os.path.join(data_dir, "bank-holidays.json")
mtime = os.path.getmtime(filename)
if (time() - mtime) > 60 * 60 * 6: # six hours
use_cached = False
events: list[StrDict]
if os.path.exists(filename):
mtime = os.path.getmtime(filename)
if (time() - mtime) < 60 * 60 * 6: # six hours
use_cached = True
try:
events = json.load(open(filename))["england-and-wales"]["events"]
except json.decoder.JSONDecodeError:
use_cached = False
if not use_cached:
async with httpx.AsyncClient() as client:
r = await client.get(url)
open(filename, "w").write(r.text)
events = json.load(open(filename))["england-and-wales"]["events"]
events = json.load(open(filename))["england-and-wales"]["events"]
hols: list[Holiday] = []
for event in events:
event_date = datetime.strptime(event["date"], "%Y-%m-%d").date()