Skip to content

Commit

Permalink
rewrite api wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
BigNocciolino committed Mar 31, 2023
1 parent 52c9214 commit 455dd11
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 42 deletions.
67 changes: 33 additions & 34 deletions custom_components/cryptostate/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,21 @@
from typing import Optional
import aiohttp
from .const import (
ALL_CURR_MIN_URL,
BASED_CURR_VALUE_URL,
ALL_CURR_URL,
BASED_MIN_CURR_VALUE_URL,
SINGLE_CURR_URL
ALL_CURR_URLS,
)


_LOGGER: logging.Logger = logging.getLogger(__package__)
HEADERS = {"Content-type": "application/json; charset=UTF-8"}

class CryptoTrackerApiClientError(Exception):
"""Error to indicate a general api error"""

class CryptoTrackerApiClientFetchingError(
CryptoTrackerApiClientError
):
"""Exception to indicate a fetching error."""

class CryptoTrackerApiClient:
"""Crypto tracker api class"""
Expand All @@ -26,46 +31,40 @@ def __init__(self, crypto: str, base: str, session: aiohttp.ClientSession) -> No
self._base = base
self._session = session

async def _format_urls():
urls = []
for url in SINGLE_CURR_URL:
url.format(crypto=self._crypto, base=self._base)
urls.append(url)
return urls

async def async_get_data(self) -> dict:
"""Get the data from the api"""
url = BASED_CURR_VALUE_URL.format(crypto=self._crypto, base=self._base)
fall = BASED_MIN_CURR_VALUE_URL.format(crypto=self._crypto, base=self._base)
return await self.api_wrapper(url=url, fallback_url=fall, headers=HEADERS)
res = await self.api_wrapper(urls=self._format_urls, headers=HEADERS)
return res

async def async_get_currecy_list(self) -> dict:
url = ALL_CURR_URL
fall = ALL_CURR_MIN_URL
return await self.api_wrapper(url=url, fallback_url=fall, headers=HEADERS)
res = await self.api_wrapper(urls=ALL_CURR_URLS, headers=HEADERS)

async def api_wrapper(
self, url: str, fallback_url: str, headers: dict = {}
self, urls: str = [], headers: dict = {}
) -> dict:
"""Get information from the api"""
try:
res = await self._session.get(url, headers=headers)
if res.ok:
return await res.json()
else:
res = await self._session.get(fallback_url, headers=headers)
return await res.json()
except asyncio.TimeoutError as exception:
_LOGGER.error(
"Timeout error fetching information from %s - %s",
url,
exception,
)

except (KeyError, TypeError) as exception:
_LOGGER.error(
"Error parsing information from %s - %s",
url,
exception,
for url in urls:
res = await self._session.get(url, headers=headers)
if res.ok:
return await res.json()
raise CryptoTrackerApiClientFetchingError(
"Can not connect to api to fetch data"
)
except asyncio.TimeoutError as exception:
raise CryptoTrackerApiClientFetchingError(
"Timeout fetching data"
)from exception
except (aiohttp.ClientError, socket.gaierror) as exception:
_LOGGER.error(
"Error fetching information from %s - %s",
url,
exception,
)
raise CryptoTrackerApiClientFetchingError(
"Fatal error fetching data"
) from exception
except Exception as exception: # pylint: disable=broad-except
_LOGGER.error("Something really wrong happened! - %s", exception)
17 changes: 9 additions & 8 deletions custom_components/cryptostate/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,14 @@

DEFAULT_NAME = "basecrypto"

SINGLE_CURR_URL = [
"https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/{crypto}/{base}.json",
"https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/{crypto}/{base}.min.json",
"https://raw.githubusercontent.com/fawazahmed0/currency-api/1/latest/currencies/{crypto}/{base}.min.json",
"https://raw.githubusercontent.com/fawazahmed0/currency-api/1/latest/currencies/{crypto}/{base}.json"
]
# With this url we can get all the currency names that are available
ALL_CURR_URL = (
"https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies.json"
)
ALL_CURR_MIN_URL = (
ALL_CURR_URLS = [
"https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies.json",
"https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies.min.json"
)
# We format this url with the vale we want to convert the currency with
BASED_CURR_VALUE_URL = "https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/{crypto}/{base}.json"
BASED_MIN_CURR_VALUE_URL = "https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/{crypto}/{base}.min.json"
]

1 comment on commit 455dd11

@fawazahmed0
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

currency-api has stopped working, Please read the migration guide

Please sign in to comment.