Prettier code

This commit is contained in:
Dominik Moritz Roth 2021-10-30 17:56:30 +02:00
parent 59bab52160
commit 69c6ee4cd0
2 changed files with 38 additions and 36 deletions

View File

@ -39,7 +39,7 @@ Print the current amount of meuros for the given amount of euros every interval-
##### When the date is set to None the current date is used. Otherwise a datetime-object is expected ##### When the date is set to None the current date is used. Otherwise a datetime-object is expected
### Cache ### Cache
Because we dont want to annoy the ecb, we cache their data while we are running and for up to an hour on disc. Because we dont want to annoy the ecb, we cache their data while we are running and for up to an hour on disc.
#### _loadYearsTable(maxCacheSeconds=3600) #### reload(maxCacheSeconds=3600)
Will reload the cache if it is older than maxCacheSeconds Will reload the cache if it is older than maxCacheSeconds
## Caveats ## Caveats
The ecb only gives an estimate for the inflation of the last month and no data for the current month. The ecb only gives an estimate for the inflation of the last month and no data for the current month.

View File

@ -6,49 +6,16 @@ from dateutil import parser as dparser
from dateutil.parser._parser import ParserError as DateParserError from dateutil.parser._parser import ParserError as DateParserError
from collections import defaultdict from collections import defaultdict
# Our inflation-table as a global-var
_years = None _years = None
def _loadYearsTable(maxCacheSeconds=3600):
global _years
if os.path.isfile('cache.json'):
with open('cache.json', 'r') as f:
cacheUpdate, cacheYears = json.loads(f.read())
if (datetime.now() - dparser.isoparse(cacheUpdate)).total_seconds() < maxCacheSeconds:
# 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()}
_years = defaultdict(lambda: {m:1 + 0.02/12 for m in range(1,13)}, cacheYears)
return
_years = _loadYearsTableWeb()
def _loadYearsTableWeb():
print('[i] Fetching new data from ECB-Servers...')
url = 'https://sdw.ecb.europa.eu/quickviewexport.do?SERIES_KEY=122.ICP.M.U2.N.000000.4.ANR&type=csv'
resp = requests.get(url)
lines = resp.text.split('\n')[6:]
years = defaultdict(lambda: {m:1 + 0.02/12 for m in range(1,13)})
for line in lines:
vals = line.split(',')
year = int(vals[0][:4])
month = datetime.strptime(vals[0][4:],'%b').month
inflation = float(vals[1])
years[year][month] = 1 + (inflation/100)/12
for year in years:
months = years[year]
for month in range(1,13):
if month not in months:
years[year][month] = 1 + 0.02/12 # Lets say the ECB archives their target
with open('cache.json', 'w') as f:
f.write(json.dumps([datetime.now().isoformat(),years]))
return years
# Gives you the exchange rate between euros and meuros for the given date. # Gives you the exchange rate between euros and meuros for the given date.
# (Should always be a float < 1) # (Should always be a float < 1)
# date should be either a datetime-object or None (= current date) # date should be either a datetime-object or None (= current date)
def exchangeRate(date=None): def exchangeRate(date=None):
global _years global _years
if _years==None: if _years==None:
_loadYearsTable() reload()
if date==None: if date==None:
date = datetime.now() date = datetime.now()
month, year = date.month, date.year month, year = date.month, date.year
@ -99,6 +66,41 @@ def _extractDate(s):
except DateParserError: except DateParserError:
return datetime.now() return datetime.now()
def reload(maxCacheSeconds=3600):
global _years
if os.path.isfile('cache.json'):
with open('cache.json', 'r') as f:
cacheUpdate, cacheYears = json.loads(f.read())
if (datetime.now() - dparser.isoparse(cacheUpdate)).total_seconds() < maxCacheSeconds:
# 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()}
_years = defaultdict(lambda: {m:1 + 0.02/12 for m in range(1,13)}, cacheYears)
return
_years = _loadYearsTableWeb()
def _loadYearsTableWeb():
print('[i] Fetching new data from ECB-Servers...')
url = 'https://sdw.ecb.europa.eu/quickviewexport.do?SERIES_KEY=122.ICP.M.U2.N.000000.4.ANR&type=csv'
resp = requests.get(url)
lines = resp.text.split('\n')[6:]
years = defaultdict(lambda: {m:1 + 0.02/12 for m in range(1,13)})
for line in lines:
vals = line.split(',')
year = int(vals[0][:4])
month = datetime.strptime(vals[0][4:],'%b').month
inflation = float(vals[1])
years[year][month] = 1 + (inflation/100)/12
for year in years:
months = years[year]
for month in range(1,13):
if month not in months:
years[year][month] = 1 + 0.02/12 # Lets say the ECB archives their target
with open('cache.json', 'w') as f:
f.write(json.dumps([datetime.now().isoformat(),years]))
return years
def cliInterface(): def cliInterface():
import sys, re import sys, re
arg = " ".join(sys.argv[1:]).replace(',','') arg = " ".join(sys.argv[1:]).replace(',','')