Changed cache workings to allow better controll when used as lib

This commit is contained in:
Dominik Moritz Roth 2021-10-30 14:19:50 +02:00
parent 237940861f
commit 872df67776

View File

@ -8,14 +8,16 @@ from dateutil.parser._parser import ParserError as DateParserError
_years = None _years = None
def _loadYearsTable(maxCacheSeconds=3600): def _loadYearsTable(maxCacheSeconds=3600):
global _years
if os.path.isfile('cache.json'): if os.path.isfile('cache.json'):
with open('cache.json', 'r') as f: with open('cache.json', 'r') as f:
cacheUpdate, cacheYears = json.loads(f.read()) cacheUpdate, cacheYears = json.loads(f.read())
if (datetime.now() - dparser.isoparse(cacheUpdate)).total_seconds() < maxCacheSeconds: if (datetime.now() - dparser.isoparse(cacheUpdate)).total_seconds() < maxCacheSeconds:
# JSON does not allow integers as keys; so we convert them back here... # JSON does not allow integers as keys; so we convert them back here...
cacheYears = {int(y):{int(m):float(n) for m,n in ms.items()} for y,ms in cacheYears.items()} cacheYears = {int(y):{int(m):float(n) for m,n in ms.items()} for y,ms in cacheYears.items()}
return cacheYears _years = cacheYears
return _loadYearsTableWeb() return
_years = _loadYearsTableWeb()
def _loadYearsTableWeb(): def _loadYearsTableWeb():
print('[i] Fetching new data from ECB-Servers...') print('[i] Fetching new data from ECB-Servers...')
@ -47,7 +49,7 @@ def _loadYearsTableWeb():
def exchangeRate(date=None): def exchangeRate(date=None):
global _years global _years
if _years==None: if _years==None:
_years = _loadYearsTable() _loadYearsTable()
if date==None: if date==None:
date = datetime.now() date = datetime.now()
month, year = date.month, date.year month, year = date.month, date.year