Spaces:
Running
Running
File size: 5,621 Bytes
97873ec fd31489 97873ec fd31489 476cee0 bb6c552 97873ec fd31489 476cee0 fd31489 476cee0 fd31489 97873ec fd31489 97873ec fd31489 bb6c552 fd31489 476cee0 fd31489 476cee0 fd31489 476cee0 fd31489 bb6c552 fd31489 bb6c552 |
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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 |
"""
Provides a robust, asynchronous PriceFetcher class for caching cryptocurrency prices.
Features:
- Asynchronous fetching using httpx.AsyncClient.
- Multi-API fallback for high availability.
- Rate-limit (429) and error handling.
- Concurrency-safe in-memory cache.
- Decoupled design for easy extension with new data sources.
"""
import asyncio
import logging
# ====================================================================
# FIX APPLIED HERE (1 of 2)
# ====================================================================
# Import Union for Python 3.9 compatibility, and other necessary types.
from typing import Callable, TypedDict, Awaitable, Union
# ====================================================================
import httpx
# --- Configuration ---
# Set up a structured logger
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
)
# Define the structure for a price parsing function
PriceParser = Callable[[dict], Awaitable[dict[str, float]]]
# Define the structure for a data source, linking a URL to its parser
class PriceSource(TypedDict):
name: str
url: str
params: dict
parser: PriceParser
# --- Main Class: PriceFetcher ---
class PriceFetcher:
"""Manages fetching and caching crypto prices from multiple APIs asynchronously."""
def __init__(self, client: httpx.AsyncClient, coins: list[str]):
"""
Initializes the PriceFetcher.
Args:
client: An instance of httpx.AsyncClient for making API calls.
coins: A list of coin IDs to fetch (e.g., ['bitcoin', 'ethereum']).
"""
self.client = client
self.coins = coins
self._prices: dict[str, Union[float, str]] = {coin: "--" for coin in coins}
self._lock = asyncio.Lock() # Lock to prevent race conditions on the cache
self.sources: list[PriceSource] = self._configure_sources()
def _configure_sources(self) -> list[PriceSource]:
"""Defines the API sources and their parsers."""
return [
{
"name": "CoinGecko",
"url": "https://api.coingecko.com/api/v3/simple/price",
"params": {
"ids": ",".join(self.coins),
"vs_currencies": "usd"
},
"parser": self._parse_coingecko,
},
{
"name": "CoinCap",
"url": "https://api.coincap.io/v2/assets",
"params": {"ids": ",".join(self.coins)},
"parser": self._parse_coincap,
},
]
async def _parse_coingecko(self, data: dict) -> dict[str, float]:
"""Parses the JSON response from CoinGecko."""
try:
return {
coin: float(data[coin]["usd"])
for coin in self.coins if coin in data
}
except (KeyError, TypeError) as e:
logging.error("β [CoinGecko] Failed to parse response: %s", e)
return {}
async def _parse_coincap(self, data: dict) -> dict[str, float]:
"""Parses the JSON response from CoinCap."""
try:
# CoinCap returns a list under the 'data' key
return {
item["id"]: float(item["priceUsd"])
for item in data.get("data", []) if item.get("id") in self.coins
}
except (KeyError, TypeError, ValueError) as e:
logging.error("β [CoinCap] Failed to parse response: %s", e)
return {}
# ====================================================================
# FIX APPLIED HERE (2 of 2)
# ====================================================================
# Changed the type hint from `float | str` to `Union[float, str]`.
def get_current_prices(self) -> dict[str, Union[float, str]]:
# ====================================================================
"""Returns a copy of the current price cache. Thread-safe read."""
return self._prices.copy()
async def update_prices_async(self) -> None:
"""
Asynchronously fetches prices, trying each source until one succeeds.
Updates the internal price cache in a concurrency-safe manner.
"""
for source in self.sources:
name, url, params, parser = source.values()
try:
resp = await self.client.get(url, params=params, timeout=10)
resp.raise_for_status()
new_prices = await parser(resp.json())
if not new_prices: # Parser failed to extract data
continue
async with self._lock:
self._prices.update(new_prices)
logging.info("β
[%s] Prices updated: %s", name, new_prices)
return # Success, so we exit the loop
except httpx.HTTPStatusError as e:
status = e.response.status_code
log_msg = f"β οΈ [{name}] HTTP error {status}"
if status == 429:
log_msg += " (Rate Limit). Trying next source..."
logging.warning(log_msg)
except (httpx.RequestError, asyncio.TimeoutError) as e:
logging.warning("β οΈ [%s] Request failed: %s. Trying next source...", name, e)
# Brief pause before trying the next API source
await asyncio.sleep(1)
logging.error("β All price APIs failed. Retaining stale prices.") |