Skip to navigation
Python script to get free exchange rates from the ECB
12.11.17
#!/usr/bin/env python import sys import argparse import requests import json import redis import time import xmltodict class Euro_currency(): def __init__(self): self.url = 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml' #free and stable source of daily currency exchange self.r = redis.StrictRedis(host='localhost', port=6379, db=0) #ini redis to cache results than check if a redis key exist and request the result if(self.r.exists('euro_currency')): print('euro_currency exists in redis!') self.rates = json.loads(self.r.get('euro_currency')) else: r = requests.get(self.url) d = dict(xmltodict.parse(r.text))['gesmes:Envelope']['Cube']['Cube']['Cube'] self.rates = {'EUR':1} for i in d: ii = dict(i) self.rates[ii['@currency']] = ii['@rate'] self.r.set('euro_currency',json.dumps(self.rates)) self.r.expire('euro_currency',7200) def get_rates(self): return self.rates def convert(self,amount=0,_from=False,_to=False): if(_from and _to): if not (_from in self.rates): return 'From currency not exists' if not (_to in self.rates): return 'To currency not exists' if(_from == 'EUR'): return round(float(amount)*float(self.rates[_to]),2) else: return round(float(amount)/float(self.rates[_from]),2) else: print(self.rates) if __name__ == "__main__": ap = argparse.ArgumentParser('Rakuten Searches ') #command line argument ap.add_argument('--a',help='Amount to convert',required=False) ap.add_argument('--f',help='From currecny',required=False) ap.add_argument('--t',help='To currecny',required=False) ap.add_argument('--r',help='Get all rates',required=False,action='store_true') args = ap.parse_args() e = Euro_currency() if(args.f and args.t and args.a): r = e.convert(args.a,args.f,args.t) elif(args.r): r = e.get_rates() print(r)
http://www.ecb.europa.eu/stats/eurofxref/
Reply
Anonymous
Information Epoch 1732672329
Build a prototype as soon as possible.
Home
Notebook
Contact us