Skip to content

Commit

Permalink
Add suopprt to get all available currencies
Browse files Browse the repository at this point in the history
  • Loading branch information
fabaff committed Jun 8, 2019
1 parent 31cd6bd commit a1e35b0
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
23 changes: 18 additions & 5 deletions aiocurrencylayer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@
class CurrencyLayer(object):
"""A class for handling the data retrieval."""

def __init__(self, loop, session, api_key, source='USD'):
def __init__(self, loop, session, api_key, source='USD', quote=None):
"""Initialize the connection to the currencylayer API."""
self._loop = loop
self._quote = quote
self._session = session
self._timestamp = self._quotes = None
self.data = {}
self.source = source
self.valid = self.free = None
Expand All @@ -26,7 +28,6 @@ def __init__(self, loop, session, api_key, source='USD'):
'access_key': api_key,
'format': 1,
}
self._timestamp = self._quotes = None

async def get_data(self):
"""Retrieve the data from currencylayer."""
Expand All @@ -39,7 +40,8 @@ async def get_data(self):
"Response from CurrencyLayer API: %s", response.status)
self.data = await response.json()
_LOGGER.debug(self.data)

self._quotes = {key.replace(self.source, ''): round(value, 4) for
key, value in self.data['quotes'].items()}
if self.data['success'] is False:
if self.data['error']['code'] == 101:
self.valid = False
Expand All @@ -60,11 +62,18 @@ def timestamp(self):
"""Return the timestamp of the quotes."""
return self.data['timestamp']

@property
def quote(self):
"""Return the requested quote."""
if self._quote is not None:
return self._quotes[self._quote]
else:
return self._quotes

@property
def quotes(self):
"""Return the available quotes."""
return {key.replace(self.source, ''): round(value, 4) for
key, value in self.data['quotes'].items()}
return self._quotes

async def validate_api_key(self):
"""Return the validity of the API key."""
Expand All @@ -73,3 +82,7 @@ async def validate_api_key(self):
async def check_free_plan(self):
"""Return True if free plan (only USD as source currency allowed)."""
return self.free

async def supported_currencies(self):
"""Return supported currencies."""
return list(self._quotes.keys())
10 changes: 9 additions & 1 deletion example.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,15 @@ async def main():
"An API key for free plan is used, only USD as source allowed")
return

print(currency.quotes)
print("Supported currencies:",
len(await currency.supported_currencies()))

# Get all quotes (identical to currency.quotes), use quote=CURRENCY
# to initialize the object to only get one currency
print(currency.quote)

# Get a single quote
print(QUOTE, currency.quotes[QUOTE])

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

0 comments on commit a1e35b0

Please sign in to comment.