|
| 1 | +"""Contains the Cube.js API client""" |
| 2 | + |
| 3 | +from datetime import datetime, timedelta |
| 4 | +from typing import Any, Dict, Optional |
| 5 | + |
| 6 | +import backoff |
| 7 | +import httpx |
| 8 | +import jwt |
| 9 | + |
| 10 | +from .query import Query |
| 11 | + |
| 12 | + |
| 13 | +class CubeClient: |
| 14 | + """Cube.js API client""" |
| 15 | + |
| 16 | + def __init__( |
| 17 | + self, |
| 18 | + host: str = "http://localhost:4000", |
| 19 | + base_path: str = "/cubejs-api", |
| 20 | + secret: Optional[str] = None, |
| 21 | + load_request_timeout: float = 30.0, |
| 22 | + token_ttl_hours: int = 1, |
| 23 | + ) -> None: |
| 24 | + """Initializer |
| 25 | +
|
| 26 | + Args: |
| 27 | + host: Cube.js API host |
| 28 | + base_path: Cube.js API base path |
| 29 | + secret: Secret for signing tokens. Set to None to skip authentication. |
| 30 | + load_request_timeout: Timeout in seconds to wait for load responses |
| 31 | + token_ttl_hours: TTL in hours for the token lifetime |
| 32 | +
|
| 33 | + """ |
| 34 | + self._secret = secret |
| 35 | + self._load_request_timeout = load_request_timeout |
| 36 | + self._token_ttl_hours = token_ttl_hours |
| 37 | + self._http_client = httpx.AsyncClient( |
| 38 | + base_url=f"{host.rstrip('/')}/{base_path.strip('/')}" |
| 39 | + ) |
| 40 | + |
| 41 | + self._token = None |
| 42 | + |
| 43 | + def _get_signed_token(self) -> Optional[str]: |
| 44 | + """Get or refresh the authentication token |
| 45 | +
|
| 46 | + Returns: |
| 47 | + token or None if no secret was configured |
| 48 | +
|
| 49 | + """ |
| 50 | + if not self._secret: |
| 51 | + return None |
| 52 | + |
| 53 | + now = datetime.now() |
| 54 | + if not self._token or self._token_expiration <= now: |
| 55 | + self._token_expiration = now + timedelta(hours=self._token_ttl_hours) |
| 56 | + self._token = jwt.encode( |
| 57 | + {"exp": self._token_expiration}, self._secret, algorithm="HS256" |
| 58 | + ) |
| 59 | + |
| 60 | + return self._token |
| 61 | + |
| 62 | + @property |
| 63 | + def token(self) -> Optional[str]: |
| 64 | + """Alias for getting the current token value""" |
| 65 | + return self._get_signed_token() |
| 66 | + |
| 67 | + async def load(self, query: Query) -> Dict[str, Any]: |
| 68 | + """Get the data for a query. |
| 69 | +
|
| 70 | + Args: |
| 71 | + query: Query object |
| 72 | +
|
| 73 | + Returns: |
| 74 | + dict with properties: |
| 75 | + * query -- The query passed via params |
| 76 | + * data -- Formatted dataset of query results |
| 77 | + * annotation -- Metadata for query. Contains descriptions for all query |
| 78 | + items. |
| 79 | + * title -- Human readable title from data schema. |
| 80 | + * shortTitle -- Short title for visualization usage (ex. chart overlay) |
| 81 | + * type -- Data type |
| 82 | +
|
| 83 | + """ |
| 84 | + return await self._request( |
| 85 | + "post", |
| 86 | + "/v1/load", |
| 87 | + body={"query": query.serialize()}, |
| 88 | + timeout=self._load_request_timeout, |
| 89 | + ) |
| 90 | + |
| 91 | + @backoff.on_exception( |
| 92 | + backoff.expo, httpx.RequestError, max_tries=8, jitter=backoff.random_jitter |
| 93 | + ) |
| 94 | + async def _request( |
| 95 | + self, method: str, path: str, body: Optional[Any] = None, timeout: float = 5.0 |
| 96 | + ): |
| 97 | + """Make API request to Cube.js server |
| 98 | +
|
| 99 | + Args: |
| 100 | + method: HTTP method |
| 101 | + path: URL path |
| 102 | + body: Body to send with the request, if applicable |
| 103 | + timeout: Request timeout in seconds |
| 104 | +
|
| 105 | + Returns: |
| 106 | + response data |
| 107 | +
|
| 108 | + """ |
| 109 | + headers = {} |
| 110 | + if self.token: |
| 111 | + headers["Authorization"] = self.token |
| 112 | + |
| 113 | + async with self._http_client as client: |
| 114 | + response = await client.request( |
| 115 | + method, path, json=body, headers=headers, timeout=timeout |
| 116 | + ) |
| 117 | + response.raise_for_status() |
| 118 | + return response.json() |
0 commit comments