File size: 2,406 Bytes
9c400b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d068566
9c400b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d068566
 
9c400b9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import os
from dotenv import load_dotenv

import httpx
from src.libs.helper_functions import convert_to_snakecase
from src.databases.redis import REDIS_CACHED
from src.libs.constants import ONE_MINUTE_IN_SECONDS
from src.libs.constants import CRYPTO_COMPARE_BASE_URL
from src.libs.logger import logger


load_dotenv()

redis_cache = REDIS_CACHED

class CryptoCompare:
    def __init__(self, base_url: str = None) -> None:
        self.CRYPTO_COMPARE_BASE_URL = base_url or CRYPTO_COMPARE_BASE_URL

    @redis_cache(ttl=ONE_MINUTE_IN_SECONDS)
    @logger.instrument()
    def get_all_coins(self) -> dict:
        url = f"{self.CRYPTO_COMPARE_BASE_URL}data/all/coinlist"
        logger.debug(url)
        params = {"api_key": os.getenv("CRYPTOCOMPARE_API_KEY")}
        logger.debug(params)
        headers = {"Content-type":"application/json; charset=UTF-8"}
        logger.debug(headers)

        try:
            with httpx.Client(timeout=30.0) as client:
                response = client.get(url, params=params, headers=headers)
                response.raise_for_status()  # Raise an exception if the request was unsuccessful
                return convert_to_snakecase(response.json())
        except httpx.HTTPError as e:
            print(f"An error occurred while making the request: {e}")
            return None
        
    @redis_cache(ttl=ONE_MINUTE_IN_SECONDS)
    @logger.instrument()
    def get_coin_price(self, ids: list[str], vs_currencies: list[str], cache_ttl: int = None) -> dict:
        
        url = f"{self.CRYPTO_COMPARE_BASE_URL}data/pricemulti"
        # logger.debug(url)

        params = {
            "api_key": os.getenv("CRYPTOCOMPARE_API_KEY"),
            "fsyms": ",".join(ids),
            "tsyms": ",".join(vs_currencies)
        }
        # logger.debug(f"{params}")

        headers = {"Content-type":"application/json; charset=UTF-8"}
        # logger.debug(f"{headers}")

        try:
            with httpx.Client(timeout=30.0) as client:
                response = client.get(url, params=params, headers=headers)
                response.raise_for_status()  # Raise an exception if the request was unsuccessful
                return response.json()
        except httpx.HTTPError as e:
            # logger.debug(f"An error occurred while making the request: {e}")
            print(f"An error occurred while making the request: {e}")
            return None