|
| 1 | +import requests |
| 2 | +import datetime |
| 3 | + |
| 4 | + |
| 5 | +class RateNotFoundError(Exception): |
| 6 | + """ |
| 7 | + Custom exception when conversion rate not found for given Country |
| 8 | + """ |
| 9 | + pass |
| 10 | + |
| 11 | + |
| 12 | +class RatesNotAvailableError(Exception): |
| 13 | + """ |
| 14 | + Custome Exception when http://fixer.io/ is Down are not available for currency rates |
| 15 | + """ |
| 16 | + pass |
| 17 | + |
| 18 | + |
| 19 | +class Common: |
| 20 | + |
| 21 | + def __init__(self): |
| 22 | + pass |
| 23 | + |
| 24 | + def _source_url(self): |
| 25 | + return "http://api.fixer.io/" |
| 26 | + |
| 27 | + def _get_date_string(self, date_str): |
| 28 | + if date_str is None: |
| 29 | + return 'latest' |
| 30 | + try: |
| 31 | + datetime.datetime.strptime(date_str, '%Y-%m-%d') |
| 32 | + return date_str |
| 33 | + except ValueError: |
| 34 | + raise ValueError("Incorrect date String, date_str should be YYYY-MM-DD") |
| 35 | + |
| 36 | + |
| 37 | +class CurrencyRates(Common): |
| 38 | + |
| 39 | + def get_rates(self, base_cur, date_str=None): |
| 40 | + date_str = self._get_date_string(date_str) |
| 41 | + payload = {'base': base_cur} |
| 42 | + source_url = self._source_url() + date_str |
| 43 | + response = requests.get(source_url, params=payload) |
| 44 | + if response.status_code == 200: |
| 45 | + rates = response.json().get('rates', {}) |
| 46 | + return rates |
| 47 | + raise RatesNotAvailableError("Currency Rates Source Not Ready") |
| 48 | + |
| 49 | + def get_rate(self, base_cur, dest_cur, date_str=None): |
| 50 | + date_str = self._get_date_string(date_str) |
| 51 | + payload = {'base': base_cur, 'symbols': dest_cur} |
| 52 | + source_url = self._source_url() + date_str |
| 53 | + response = requests.get(source_url, params=payload) |
| 54 | + if response.status_code == 200: |
| 55 | + rate = response.json().get('rates', {}).get(dest_cur) |
| 56 | + if not rate: |
| 57 | + raise RatesNotAvailableError("Currency Rate {0} => {1} not available for Date {2}".format( |
| 58 | + base_cur, dest_cur, date_str)) |
| 59 | + return rate |
| 60 | + raise RatesNotAvailableError("Currency Rates Source Not Ready") |
| 61 | + |
| 62 | + def convert(self, base_cur, dest_cur, amount, date_str=None): |
| 63 | + date_str = self._get_date_string(date_str) |
| 64 | + payload = {'base': base_cur, 'symbols': dest_cur} |
| 65 | + source_url = self._source_url() + date_str |
| 66 | + response = requests.get(source_url, params=payload) |
| 67 | + if response.status_code == 200: |
| 68 | + rate = response.json().get('rates', {}).get(dest_cur, None) |
| 69 | + if not rate: |
| 70 | + raise RatesNotAvailableError("Currency {0} => {1} rate not available for Date {2}.".format( |
| 71 | + source_url, dest_cur, date_str)) |
| 72 | + converted_amount = rate * amount |
| 73 | + return converted_amount |
| 74 | + raise RatesNotAvailableError("Currency Rates Source Not Ready") |
0 commit comments