Code3 PDF - 6635ad4963e35
Code3 PDF - 6635ad4963e35
import requests
import simplejson as json
class RatesNotAvailableError(Exception):
"""
Custom exception when https://theforexapi.com is down and not available for currency rates
"""
pass
class DecimalFloatMismatchError(Exception):
"""
A float has been supplied when force_decimal was set to True
"""
pass
class Common:
def _source_url(self):
return "https://theforexapi.com/api/"
def _get_decoded_rate(
self, response, dest_cur, use_decimal=False, date_str=None):
return self._decode_rates(
response, use_decimal=use_decimal, date_str=date_str).get(
dest_cur, None)
class CurrencyRates(Common):
if base_cur == dest_cur: # Return same amount if both base_cur, dest_cur are same
if use_decimal:
return Decimal(amount)
return float(amount)
date_str = self._get_date_string(date_obj)
payload = {'base': base_cur, 'symbols': dest_cur, 'rtype': 'fpy'}
source_url = self._source_url() + date_str
response = requests.get(source_url, params=payload)
if response.status_code == 200:
rate = self._get_decoded_rate(
response, dest_cur, use_decimal=use_decimal, date_str=date_str)
if not rate:
raise RatesNotAvailableError("Currency {0} => {1} rate not available for Date {2}.".format(
source_url, dest_cur, date_str))
try:
converted_amount = rate * amount
return converted_amount
except TypeError:
raise DecimalFloatMismatchError(
"convert requires amount parameter is of type Decimal when force_decimal=True")
raise RatesNotAvailableError("Currency Rates Source Not Ready")
_CURRENCY_FORMATTER = CurrencyRates()
get_rates = _CURRENCY_FORMATTER.get_rates
get_rate = _CURRENCY_FORMATTER.get_rate
convert = _CURRENCY_FORMATTER.convert
class CurrencyCodes:
def __init__(self):
self.__currency_data = None
@property
def _currency_data(self):
if self.__currency_data is None:
file_path = os.path.dirname(os.path.abspath(__file__))
with open(file_path + '/raw_data/currencies.json') as f:
self.__currency_data = json.loads(f.read())
return self.__currency_data
_CURRENCY_CODES = CurrencyCodes()
get_symbol = _CURRENCY_CODES.get_symbol
get_currency_name = _CURRENCY_CODES.get_currency_name
get_currency_code_from_symbol = _CURRENCY_CODES.get_currency_code_from_symbol