84 lines
2.5 KiB
Python
84 lines
2.5 KiB
Python
import argparse
|
|
import httpx
|
|
import json
|
|
import datetime
|
|
|
|
|
|
class MiIndicador:
|
|
def __init__(self, base_url: str = None):
|
|
print('Creating object Mindicador')
|
|
|
|
if base_url is None:
|
|
base_url = 'https://mindicador.cl/api'
|
|
self.base_url = base_url
|
|
|
|
def __build_url(self, sub_url: str, query: str = ''):
|
|
sub = sub_url
|
|
if query != '':
|
|
sub = '?'.join([
|
|
sub,
|
|
query
|
|
])
|
|
url = '/'.join([
|
|
self.base_url,
|
|
sub
|
|
])
|
|
return url
|
|
|
|
def __get(self, url: str):
|
|
resp = httpx.get(url)
|
|
if resp.status_code != httpx.codes.OK:
|
|
raise Exception(resp.reason_phrase)
|
|
return json.loads(resp.text)
|
|
|
|
def list(self):
|
|
print('List possible indicators')
|
|
|
|
url = self.__build_url('')
|
|
return self.__get(url)
|
|
|
|
def get(self, indicador: str, fecha: str = None):
|
|
print('Getting {} in date {} from {}'.format(indicador, fecha, self.base_url))
|
|
|
|
url = indicador
|
|
if fecha is not None:
|
|
url = '/'.join([url, fecha])
|
|
url = self.__build_url(url)
|
|
res = self.__get(url)
|
|
for i, item in enumerate(res['serie']):
|
|
res['serie'][i]['fecha'] = datetime.datetime.fromisoformat(item['fecha'].replace('T', ' ').replace('Z', ''))\
|
|
.strftime('%Y-%m-%d')
|
|
return res
|
|
|
|
def historical(self, indicador: str, since: str = None):
|
|
print('Getting historical data for {} since {} from {}'.format(indicador, since, self.base_url))
|
|
|
|
sub = indicador
|
|
if since is not None:
|
|
sub = '/'.join([sub, since])
|
|
url = self.__build_url(sub)
|
|
res = self.__get(url)
|
|
for i, item in enumerate(res['serie']):
|
|
res['serie'][i]['fecha'] = datetime.datetime.fromisoformat(item['fecha'].replace('T', ' ').replace('Z', ''))\
|
|
.strftime('%Y-%m-%d')
|
|
return res
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('-u', '--url')
|
|
parser.add_argument('-i', '--indicador')
|
|
hist = parser.add_subparsers()
|
|
hparser = hist.add_parser('hist')
|
|
hparser.add_argument('-hi', '--historical', action='store_true')
|
|
hparser.add_argument('-s', '--since')
|
|
args = parser.parse_args()
|
|
|
|
print('Called with args: {}'.format(vars(args)))
|
|
|
|
mi = MiIndicador(args.url)
|
|
if 'historical' in args and args.historical:
|
|
print(mi.historical(args.indicador, args.since))
|
|
exit()
|
|
print(mi.get(args.indicador))
|