|
| 1 | +import requests |
| 2 | +from collections import namedtuple |
| 3 | +from urllib.parse import urlencode, urlunparse |
| 4 | + |
| 5 | +from .config import Region |
| 6 | +from .exceptions import * |
| 7 | + |
| 8 | +class ExchangerateClient: |
| 9 | + """ |
| 10 | + Primary client class |
| 11 | + """ |
| 12 | + def __init__(self, base_currency="USD", region=Region.AMERICA): |
| 13 | + self.base_currency = base_currency |
| 14 | + self.region = region |
| 15 | + self.session = requests.Session() |
| 16 | + |
| 17 | + # ------------------------------------------------------------------- |
| 18 | + # Public methods |
| 19 | + # ------------------------------------------------------------------- |
| 20 | + |
| 21 | + def symbols(self): |
| 22 | + url = self._build_url(path="symbols") |
| 23 | + resp_json = self._validate_and_get_json(url) |
| 24 | + return resp_json.get("rates") |
| 25 | + |
| 26 | + # ------------------------------------------------------------------- |
| 27 | + def _validate_and_get_json(self, url): |
| 28 | + resp = self.session.get(url) |
| 29 | + if resp.status_code != 200: |
| 30 | + raise ResponseErrorException("Status code=%d calling url=%s" % (resp.status_code, url)) |
| 31 | + |
| 32 | + resp_json = resp.json() |
| 33 | + if not resp_json.get("success", False): |
| 34 | + raise ResponseErrorException("No success field calling url=%s" % (url)) |
| 35 | + |
| 36 | + return resp_json |
| 37 | + |
| 38 | + def _build_url(self, path="", params=None): |
| 39 | + Components = namedtuple( |
| 40 | + typename='Components', |
| 41 | + field_names=['scheme', 'netloc', 'url', 'path', 'query', 'fragment'] |
| 42 | + ) |
| 43 | + |
| 44 | + if not params: |
| 45 | + params = {} |
| 46 | + |
| 47 | + return urlunparse( |
| 48 | + Components( |
| 49 | + scheme='https', |
| 50 | + netloc=self.region.value, |
| 51 | + query=urlencode(params), |
| 52 | + path=path, |
| 53 | + url="/", |
| 54 | + fragment="" |
| 55 | + ) |
| 56 | + ) |
0 commit comments