New arguments to handle cache expiration

This commit is contained in:
nemunaire 2022-12-30 19:54:21 +01:00
commit f79022b7a3
5 changed files with 65 additions and 25 deletions

View file

@ -13,12 +13,13 @@ class SNCFAPI:
CLEANR = re.compile('<.*?>')
def __init__(self):
def __init__(self, config):
self.baseurl = "https://www.sncf.com/api/iv"
self.auth = base64.b64encode(b"admin:$2y$10$QvxWSS4f5DIFSkAmuBoV9OJG3M2bhec9d3F2.YnULBMtpzKAq2KS.").decode()
self._cached_file = ".sncf-%d-%s.cache"
self.cache_time = 5
self.cache_timeout = config.cache_timeout
self.max_cache_timeout = config.max_cache_timeout
def get_icon(size):
height = int(size * 0.531)
@ -39,7 +40,7 @@ class SNCFAPI:
except:
pass
if statinfo is None or datetime.fromtimestamp(statinfo.st_mtime, tz=timezone.utc) + timedelta(minutes=self.cache_time) < datetime.now(tz=timezone.utc):
if statinfo is None or datetime.fromtimestamp(statinfo.st_mtime, tz=timezone.utc) + timedelta(minutes=self.cache_timeout) < datetime.now(tz=timezone.utc):
# Do the request and save it
req = urllib.request.Request(self.baseurl + "/1.0/infoVoy/rechercherListeCirculations?numero=%d&dateCirculation=%s&codeZoneArret&typeHoraire=TEMPS_REEL" % (int(numero), date.strftime("%Y-%m-%d")), headers={'Authorization': "Basic " + self.auth})
try:
@ -51,6 +52,14 @@ class SNCFAPI:
except urllib.error.URLError:
pass
try:
statinfo = os.stat(cache_file)
except:
pass
if statinfo is None or datetime.fromtimestamp(statinfo.st_mtime, tz=timezone.utc) + timedelta(minutes=self.max_cache_timeout) < datetime.now(tz=timezone.utc):
raise Exception("File too old")
# Retrieve cached data
res = {}
with open(cache_file) as f:
@ -70,7 +79,7 @@ class SNCFAPI:
except:
pass
if statinfo is None or datetime.fromtimestamp(statinfo.st_mtime, tz=timezone.utc) + timedelta(minutes=self.cache_time) < datetime.now(tz=timezone.utc):
if statinfo is None or datetime.fromtimestamp(statinfo.st_mtime, tz=timezone.utc) + timedelta(minutes=self.cache_timeout) < datetime.now(tz=timezone.utc):
# Do the request and save it
req = urllib.request.Request(self.baseurl + "/edito/bandeaux?region=%s" % (region), headers={'Authorization': "Basic " + self.auth})
try:
@ -82,6 +91,14 @@ class SNCFAPI:
except urllib.error.URLError:
pass
try:
statinfo = os.stat(cache_file)
except:
pass
if statinfo is None or datetime.fromtimestamp(statinfo.st_mtime, tz=timezone.utc) + timedelta(minutes=self.max_cache_timeout) < datetime.now(tz=timezone.utc):
raise Exception("File too old")
# Retrieve cached data
res = {}
with open(cache_file) as f:
@ -95,10 +112,10 @@ class SNCFWeatherModule:
def __init__(self):
pass
def gen_alerts(self, region):
def gen_alerts(self, config, region):
alerts = []
weather = SNCFAPI().get_weather(region)
weather = SNCFAPI(config).get_weather(region)
for alert in weather:
if alert["type"] != "perturbation":
continue