|
| 1 | +"""Datons API client. |
| 2 | +
|
| 3 | +Central entry point that lazily initializes product-specific managers. |
| 4 | +""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import os |
| 9 | +from typing import Any |
| 10 | + |
| 11 | +import httpx |
| 12 | + |
| 13 | +from datons.exceptions import AuthenticationError, DatonsError, QueryError, RateLimitError |
| 14 | + |
| 15 | +DEFAULT_BASE_URL = "https://mcp.datons.com" |
| 16 | +DEFAULT_TIMEOUT = 30.0 |
| 17 | + |
| 18 | + |
| 19 | +class Client: |
| 20 | + """Client for Datons data APIs. |
| 21 | +
|
| 22 | + Usage:: |
| 23 | +
|
| 24 | + from datons import Client |
| 25 | +
|
| 26 | + client = Client(token="esd_live_...") |
| 27 | + df = client.esios_data.query("SELECT unit, energy FROM operational_data_15min WHERE program='PDBF' LIMIT 10") |
| 28 | +
|
| 29 | + Or with context manager:: |
| 30 | +
|
| 31 | + with Client(token="esd_live_...") as client: |
| 32 | + df = client.esios_data.query("SELECT ...") |
| 33 | + """ |
| 34 | + |
| 35 | + def __init__( |
| 36 | + self, |
| 37 | + token: str | None = None, |
| 38 | + *, |
| 39 | + base_url: str = DEFAULT_BASE_URL, |
| 40 | + timeout: float = DEFAULT_TIMEOUT, |
| 41 | + ): |
| 42 | + self.token = token or os.getenv("DATONS_API_KEY") |
| 43 | + if not self.token: |
| 44 | + raise DatonsError( |
| 45 | + "API key required. Pass token= or set DATONS_API_KEY env var." |
| 46 | + ) |
| 47 | + |
| 48 | + self.base_url = base_url.rstrip("/") |
| 49 | + self.timeout = timeout |
| 50 | + |
| 51 | + self._http = httpx.Client( |
| 52 | + base_url=self.base_url, |
| 53 | + headers={ |
| 54 | + "X-API-Key": self.token, |
| 55 | + "User-Agent": "python-datons/0.1.0", |
| 56 | + }, |
| 57 | + timeout=self.timeout, |
| 58 | + ) |
| 59 | + |
| 60 | + # Lazy-initialized managers |
| 61 | + self._esios_data: Any = None |
| 62 | + |
| 63 | + @property |
| 64 | + def esios_data(self): |
| 65 | + """Access ESIOS preprocessed data (I90, market programs).""" |
| 66 | + if self._esios_data is None: |
| 67 | + from datons.esios_data.manager import EsiosDataManager |
| 68 | + |
| 69 | + self._esios_data = EsiosDataManager(self) |
| 70 | + return self._esios_data |
| 71 | + |
| 72 | + # -- HTTP primitives (used by managers) ------------------------------------ |
| 73 | + |
| 74 | + def get(self, path: str, params: dict[str, Any] | None = None) -> dict: |
| 75 | + """Issue a GET request.""" |
| 76 | + return self._request("GET", path, params=params) |
| 77 | + |
| 78 | + def post(self, path: str, json: dict[str, Any] | None = None) -> dict: |
| 79 | + """Issue a POST request.""" |
| 80 | + return self._request("POST", path, json=json) |
| 81 | + |
| 82 | + def _request( |
| 83 | + self, |
| 84 | + method: str, |
| 85 | + path: str, |
| 86 | + params: dict[str, Any] | None = None, |
| 87 | + json: dict[str, Any] | None = None, |
| 88 | + ) -> dict: |
| 89 | + """Execute an HTTP request with error handling.""" |
| 90 | + try: |
| 91 | + response = self._http.request(method, path, params=params, json=json) |
| 92 | + except httpx.ConnectError as exc: |
| 93 | + raise DatonsError(f"Connection failed: {exc}") from exc |
| 94 | + except httpx.TimeoutException as exc: |
| 95 | + raise DatonsError(f"Request timed out: {exc}") from exc |
| 96 | + |
| 97 | + if response.status_code == 401: |
| 98 | + raise AuthenticationError() |
| 99 | + if response.status_code == 429: |
| 100 | + retry_after = response.headers.get("Retry-After") |
| 101 | + raise RateLimitError(int(retry_after) if retry_after else None) |
| 102 | + if response.status_code >= 400: |
| 103 | + detail = response.text[:500] |
| 104 | + raise QueryError(response.status_code, detail) |
| 105 | + |
| 106 | + return response.json() |
| 107 | + |
| 108 | + # -- Lifecycle ------------------------------------------------------------- |
| 109 | + |
| 110 | + def close(self) -> None: |
| 111 | + """Close the underlying HTTP connection.""" |
| 112 | + self._http.close() |
| 113 | + |
| 114 | + def __enter__(self) -> Client: |
| 115 | + return self |
| 116 | + |
| 117 | + def __exit__(self, *args: Any) -> None: |
| 118 | + self.close() |
| 119 | + |
| 120 | + def __repr__(self) -> str: |
| 121 | + masked = self.token[:8] + "..." if self.token else "None" |
| 122 | + return f"Client(token='{masked}', base_url='{self.base_url}')" |
0 commit comments