datafortennis 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- datafortennis/__init__.py +42 -0
- datafortennis/_transport.py +375 -0
- datafortennis/_types.py +63 -0
- datafortennis/_version.py +1 -0
- datafortennis/client.py +68 -0
- datafortennis/errors.py +87 -0
- datafortennis/models.py +891 -0
- datafortennis/py.typed +0 -0
- datafortennis/resources/__init__.py +1 -0
- datafortennis/resources/_base.py +180 -0
- datafortennis/resources/catalogue.py +286 -0
- datafortennis/resources/exports.py +91 -0
- datafortennis/resources/free.py +49 -0
- datafortennis/resources/live.py +181 -0
- datafortennis/resources/matches.py +256 -0
- datafortennis/resources/research.py +149 -0
- datafortennis-0.1.0.dist-info/METADATA +136 -0
- datafortennis-0.1.0.dist-info/RECORD +19 -0
- datafortennis-0.1.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Python client for DataForTennis."""
|
|
2
|
+
|
|
3
|
+
from ._types import Page, Response
|
|
4
|
+
from ._version import __version__
|
|
5
|
+
from .client import DataForTennis
|
|
6
|
+
from .errors import (
|
|
7
|
+
AmbiguousIdentityError,
|
|
8
|
+
APIError,
|
|
9
|
+
AuthenticationError,
|
|
10
|
+
AuthorizationError,
|
|
11
|
+
ConflictError,
|
|
12
|
+
DataForTennisError,
|
|
13
|
+
IdentityCandidate,
|
|
14
|
+
NotFoundError,
|
|
15
|
+
ProtocolError,
|
|
16
|
+
QuotaExceededError,
|
|
17
|
+
RateLimitError,
|
|
18
|
+
ServerError,
|
|
19
|
+
TransportError,
|
|
20
|
+
)
|
|
21
|
+
from .resources._base import Collection
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"APIError",
|
|
25
|
+
"AmbiguousIdentityError",
|
|
26
|
+
"AuthenticationError",
|
|
27
|
+
"AuthorizationError",
|
|
28
|
+
"Collection",
|
|
29
|
+
"ConflictError",
|
|
30
|
+
"DataForTennis",
|
|
31
|
+
"DataForTennisError",
|
|
32
|
+
"IdentityCandidate",
|
|
33
|
+
"NotFoundError",
|
|
34
|
+
"Page",
|
|
35
|
+
"ProtocolError",
|
|
36
|
+
"QuotaExceededError",
|
|
37
|
+
"RateLimitError",
|
|
38
|
+
"Response",
|
|
39
|
+
"ServerError",
|
|
40
|
+
"TransportError",
|
|
41
|
+
"__version__",
|
|
42
|
+
]
|
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
"""One-origin synchronous HTTP transport shared by the SDK resources."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import time
|
|
9
|
+
from collections.abc import Iterator
|
|
10
|
+
from contextlib import contextmanager
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
from email.utils import parsedate_to_datetime
|
|
13
|
+
from ipaddress import ip_address
|
|
14
|
+
from typing import Literal, final
|
|
15
|
+
from urllib.parse import urlsplit
|
|
16
|
+
from uuid import uuid4
|
|
17
|
+
|
|
18
|
+
import httpx
|
|
19
|
+
|
|
20
|
+
from ._types import JsonObject, Query, Response, Shape, parse_envelope
|
|
21
|
+
from ._version import __version__
|
|
22
|
+
from .errors import (
|
|
23
|
+
AmbiguousIdentityError,
|
|
24
|
+
APIError,
|
|
25
|
+
AuthenticationError,
|
|
26
|
+
AuthorizationError,
|
|
27
|
+
ConflictError,
|
|
28
|
+
IdentityCandidate,
|
|
29
|
+
NotFoundError,
|
|
30
|
+
ProtocolError,
|
|
31
|
+
QuotaExceededError,
|
|
32
|
+
RateLimitError,
|
|
33
|
+
ServerError,
|
|
34
|
+
TransportError,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
DEFAULT_BASE_URL = "https://api.datafortennis.com"
|
|
38
|
+
_MAX_RETRY_DELAY = 5.0
|
|
39
|
+
_RATE_CODES = {"RATE_LIMIT", "CONCURRENCY_LIMIT", "QUEUE_FULL", "QUEUE_WAIT_TIMEOUT"}
|
|
40
|
+
_QUOTA_CODES = {"PERIOD_QUOTA_EXCEEDED", "QUOTA_LIMIT"}
|
|
41
|
+
_TRANSIENT_STATUSES = {502, 503, 504}
|
|
42
|
+
_KEY_PATTERN = re.compile(r"[A-Za-z0-9_.:-]{8,128}")
|
|
43
|
+
_UNSAFE_PATH = re.compile(
|
|
44
|
+
r"[\\?#\x00-\x20\x7f]|%(?:2f|5c|2e|25)|(?:^|/)\.{1,2}(?:/|$)", re.IGNORECASE
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _origin(raw: str) -> httpx.URL:
|
|
49
|
+
try:
|
|
50
|
+
split = urlsplit(raw)
|
|
51
|
+
url = httpx.URL(raw)
|
|
52
|
+
except (ValueError, httpx.InvalidURL):
|
|
53
|
+
url = None
|
|
54
|
+
if (
|
|
55
|
+
url is None
|
|
56
|
+
or not url.host
|
|
57
|
+
or not url.is_absolute_url
|
|
58
|
+
or url.userinfo
|
|
59
|
+
or "@" in split.netloc
|
|
60
|
+
or split.path not in ("", "/")
|
|
61
|
+
or "?" in raw
|
|
62
|
+
or "#" in raw
|
|
63
|
+
or re.search(r"[\\\x00-\x20\x7f]", raw)
|
|
64
|
+
):
|
|
65
|
+
raise ValueError("base_url must be an origin without credentials, path, query or fragment")
|
|
66
|
+
try:
|
|
67
|
+
loopback = ip_address(url.host).is_loopback
|
|
68
|
+
except ValueError:
|
|
69
|
+
loopback = url.host == "localhost"
|
|
70
|
+
if url.scheme != "https" and not (url.scheme == "http" and loopback):
|
|
71
|
+
raise ValueError("base_url requires HTTPS outside loopback")
|
|
72
|
+
return url
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _retry_after(raw: str | None) -> float | None:
|
|
76
|
+
if raw is None or len(raw) > 128:
|
|
77
|
+
return None
|
|
78
|
+
if re.fullmatch(r"[0-9]+", raw):
|
|
79
|
+
return float(raw)
|
|
80
|
+
try:
|
|
81
|
+
date = parsedate_to_datetime(raw)
|
|
82
|
+
if date.tzinfo is None:
|
|
83
|
+
return None
|
|
84
|
+
return max(0.0, (date - datetime.now(timezone.utc)).total_seconds())
|
|
85
|
+
except (TypeError, ValueError, OverflowError):
|
|
86
|
+
return None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _identity_results(rows: object) -> tuple[IdentityCandidate, ...]:
|
|
90
|
+
if not isinstance(rows, list) or len(rows) > 50:
|
|
91
|
+
raise ProtocolError("Invalid identity conflict response")
|
|
92
|
+
results = []
|
|
93
|
+
for row in rows:
|
|
94
|
+
if not isinstance(row, dict):
|
|
95
|
+
raise ProtocolError("Invalid identity result")
|
|
96
|
+
index, status, ids = row.get("index"), row.get("status"), row.get("own_ids")
|
|
97
|
+
if (
|
|
98
|
+
type(index) is not int
|
|
99
|
+
or not 0 <= index < 50
|
|
100
|
+
or status not in ("ambiguous", "unresolved", "resolved")
|
|
101
|
+
or not isinstance(ids, list)
|
|
102
|
+
or len(ids) > 6
|
|
103
|
+
or not all(
|
|
104
|
+
isinstance(item, str) and re.fullmatch(r"(mat|ply)_[a-f0-9-]{36}", item)
|
|
105
|
+
for item in ids
|
|
106
|
+
)
|
|
107
|
+
or len(set(ids)) != len(ids)
|
|
108
|
+
):
|
|
109
|
+
raise ProtocolError("Invalid identity result")
|
|
110
|
+
results.append(IdentityCandidate(index, status, tuple(ids)))
|
|
111
|
+
return tuple(results)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _validate_export_range(
|
|
115
|
+
requested: str | None,
|
|
116
|
+
response: httpx.Response,
|
|
117
|
+
) -> None:
|
|
118
|
+
if requested is None:
|
|
119
|
+
if response.status_code != 200:
|
|
120
|
+
raise ProtocolError("Unexpected partial export")
|
|
121
|
+
return
|
|
122
|
+
if response.status_code != 206:
|
|
123
|
+
raise ProtocolError("The server did not honor the requested export range")
|
|
124
|
+
if response.headers.get("Content-Encoding", "identity").lower() != "identity":
|
|
125
|
+
raise ProtocolError("Unexpected encoding on a ranged export")
|
|
126
|
+
served = re.fullmatch(
|
|
127
|
+
r"bytes ([0-9]{1,30})-([0-9]{1,30})/([0-9]{1,30})",
|
|
128
|
+
response.headers.get("Content-Range", ""),
|
|
129
|
+
)
|
|
130
|
+
wanted = re.fullmatch(r"bytes=([0-9]{0,30})-([0-9]{0,30})", requested)
|
|
131
|
+
if not served or not wanted or not any(wanted.groups()):
|
|
132
|
+
raise ProtocolError("Invalid export range")
|
|
133
|
+
first, last, size = map(int, served.groups())
|
|
134
|
+
start, end = wanted.groups()
|
|
135
|
+
expect_first = int(start) if start else max(0, size - int(end))
|
|
136
|
+
expect_last = min(int(end), size - 1) if start and end else size - 1
|
|
137
|
+
if not 0 <= first <= last < size or (first, last) != (expect_first, expect_last):
|
|
138
|
+
raise ProtocolError("Returned export range differs from the requested range")
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class Download:
|
|
142
|
+
"""Streaming file and response metadata, valid within the download context."""
|
|
143
|
+
|
|
144
|
+
def __init__(self, response: httpx.Response) -> None:
|
|
145
|
+
self._response = response
|
|
146
|
+
self.status_code = response.status_code
|
|
147
|
+
self.headers = httpx.Headers(
|
|
148
|
+
{
|
|
149
|
+
name: response.headers[name]
|
|
150
|
+
for name in (
|
|
151
|
+
"ETag",
|
|
152
|
+
"Content-Type",
|
|
153
|
+
"Content-Length",
|
|
154
|
+
"Content-Range",
|
|
155
|
+
"Accept-Ranges",
|
|
156
|
+
"X-Operation-Id",
|
|
157
|
+
)
|
|
158
|
+
if name in response.headers
|
|
159
|
+
}
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]:
|
|
163
|
+
try:
|
|
164
|
+
yield from self._response.iter_bytes(chunk_size=chunk_size)
|
|
165
|
+
return
|
|
166
|
+
except (httpx.RequestError, httpx.StreamError):
|
|
167
|
+
pass
|
|
168
|
+
raise TransportError("The export stream could not be read")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@final
|
|
172
|
+
class Transport:
|
|
173
|
+
"""Owns a pooled HTTPX client and closes an injected HTTPX transport with it."""
|
|
174
|
+
|
|
175
|
+
def __init__(
|
|
176
|
+
self,
|
|
177
|
+
api_key: str | None = None,
|
|
178
|
+
*,
|
|
179
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
180
|
+
timeout: float | httpx.Timeout = 10.0,
|
|
181
|
+
max_retries: int = 2,
|
|
182
|
+
transport: httpx.BaseTransport | None = None,
|
|
183
|
+
) -> None:
|
|
184
|
+
self._origin = _origin(base_url)
|
|
185
|
+
if type(max_retries) is not int or not 0 <= max_retries <= 5:
|
|
186
|
+
raise ValueError("max_retries must be an integer from 0 to 5")
|
|
187
|
+
if not isinstance(timeout, httpx.Timeout) and (
|
|
188
|
+
isinstance(timeout, bool)
|
|
189
|
+
or not isinstance(timeout, (float, int))
|
|
190
|
+
or not math.isfinite(timeout)
|
|
191
|
+
or timeout <= 0
|
|
192
|
+
):
|
|
193
|
+
raise ValueError("timeout must be positive and finite")
|
|
194
|
+
self._max_retries = max_retries
|
|
195
|
+
self._key = os.getenv("DATAFORTENNIS_API_KEY") if api_key is None else api_key
|
|
196
|
+
if self._key is not None and not re.fullmatch(r"[!-~]{1,2048}", self._key):
|
|
197
|
+
raise ValueError("API key must contain only printable non-space ASCII characters")
|
|
198
|
+
self._client = httpx.Client(
|
|
199
|
+
base_url=self._origin,
|
|
200
|
+
timeout=timeout,
|
|
201
|
+
transport=transport,
|
|
202
|
+
follow_redirects=False,
|
|
203
|
+
trust_env=False,
|
|
204
|
+
headers={"User-Agent": f"datafortennis-python/{__version__}", "Accept": "application/json"},
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
def close(self) -> None:
|
|
208
|
+
self._client.close()
|
|
209
|
+
|
|
210
|
+
def __enter__(self) -> Transport:
|
|
211
|
+
if self._client.is_closed:
|
|
212
|
+
raise TransportError("The client is closed")
|
|
213
|
+
return self
|
|
214
|
+
|
|
215
|
+
def __exit__(self, *exc: object) -> None:
|
|
216
|
+
self.close()
|
|
217
|
+
|
|
218
|
+
def _headers(self, path: str, public: bool) -> dict[str, str]:
|
|
219
|
+
if not path.startswith("/") or "//" in path or _UNSAFE_PATH.search(path):
|
|
220
|
+
raise ValueError("Expected an API path on the configured origin")
|
|
221
|
+
if self._client.is_closed:
|
|
222
|
+
raise TransportError("The client is closed")
|
|
223
|
+
if public:
|
|
224
|
+
return {}
|
|
225
|
+
if self._key is None:
|
|
226
|
+
raise AuthenticationError(401, "MISSING_API_KEY")
|
|
227
|
+
return {"Authorization": f"Bearer {self._key}"}
|
|
228
|
+
|
|
229
|
+
def _safe_field(self, value: object, pattern: str) -> str | None:
|
|
230
|
+
if not isinstance(value, str) or not re.fullmatch(pattern, value):
|
|
231
|
+
return None
|
|
232
|
+
if self._key and self._key in value:
|
|
233
|
+
return None
|
|
234
|
+
return value
|
|
235
|
+
|
|
236
|
+
def _identifier(self, value: object) -> str | None:
|
|
237
|
+
return self._safe_field(value, r"[a-zA-Z0-9_-]{1,128}")
|
|
238
|
+
|
|
239
|
+
def _error(self, response: httpx.Response) -> APIError:
|
|
240
|
+
try:
|
|
241
|
+
body = response.json()
|
|
242
|
+
except (UnicodeError, ValueError, RecursionError):
|
|
243
|
+
body = {}
|
|
244
|
+
# The onboarding API uses a flat code. REST uses error.code and error.request_id.
|
|
245
|
+
detail = body.get("error", body) if isinstance(body, dict) else {}
|
|
246
|
+
if not isinstance(detail, dict):
|
|
247
|
+
detail = {}
|
|
248
|
+
code = self._safe_field(detail.get("code"), r"[A-Z][A-Z0-9_]{0,80}") or "HTTP_ERROR"
|
|
249
|
+
request_id = self._identifier(detail.get("request_id")) or self._identifier(
|
|
250
|
+
response.headers.get("X-Request-Id")
|
|
251
|
+
)
|
|
252
|
+
status = response.status_code
|
|
253
|
+
if status == 409 and code == "AMBIGUOUS_IDENTITY":
|
|
254
|
+
return AmbiguousIdentityError(
|
|
255
|
+
_identity_results(body.get("data")), request_id=request_id
|
|
256
|
+
)
|
|
257
|
+
kind: type[APIError] = {
|
|
258
|
+
401: AuthenticationError,
|
|
259
|
+
403: AuthorizationError,
|
|
260
|
+
404: NotFoundError,
|
|
261
|
+
409: ConflictError,
|
|
262
|
+
429: RateLimitError,
|
|
263
|
+
}.get(status, APIError)
|
|
264
|
+
if status == 429 and code in _QUOTA_CODES:
|
|
265
|
+
kind = QuotaExceededError
|
|
266
|
+
if 500 <= status < 600:
|
|
267
|
+
kind = ServerError
|
|
268
|
+
return kind(
|
|
269
|
+
status,
|
|
270
|
+
code,
|
|
271
|
+
request_id=request_id,
|
|
272
|
+
retry_after=_retry_after(response.headers.get("Retry-After")),
|
|
273
|
+
content_range=self._safe_field(
|
|
274
|
+
response.headers.get("Content-Range"), r"bytes \*/[0-9]{1,30}"
|
|
275
|
+
)
|
|
276
|
+
if status == 416
|
|
277
|
+
else None,
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
def request(
|
|
281
|
+
self,
|
|
282
|
+
method: Literal["GET", "POST", "DELETE"],
|
|
283
|
+
path: str,
|
|
284
|
+
*,
|
|
285
|
+
params: Query | None = None,
|
|
286
|
+
json: object = None,
|
|
287
|
+
public: bool = False,
|
|
288
|
+
supports_idempotency: bool = False,
|
|
289
|
+
idempotency_key: str | None = None,
|
|
290
|
+
expected: Shape = "either",
|
|
291
|
+
) -> Response[JsonObject | list[JsonObject]]:
|
|
292
|
+
headers = self._headers(path, public)
|
|
293
|
+
if idempotency_key is not None and (
|
|
294
|
+
not supports_idempotency or not _KEY_PATTERN.fullmatch(idempotency_key)
|
|
295
|
+
):
|
|
296
|
+
raise ValueError("Invalid or unsupported idempotency key")
|
|
297
|
+
if supports_idempotency:
|
|
298
|
+
# One key per logical request, shared by every attempt at that request.
|
|
299
|
+
headers["Idempotency-Key"] = idempotency_key or str(uuid4())
|
|
300
|
+
query = {k: v for k, v in (params or {}).items() if v is not None}
|
|
301
|
+
retries = self._max_retries if method == "GET" and (public or supports_idempotency) else 0
|
|
302
|
+
for attempt in range(retries + 1):
|
|
303
|
+
try:
|
|
304
|
+
response = self._client.request(
|
|
305
|
+
method, path, headers=headers, params=query, json=json
|
|
306
|
+
)
|
|
307
|
+
except (httpx.NetworkError, httpx.TimeoutException, httpx.RemoteProtocolError):
|
|
308
|
+
response = None
|
|
309
|
+
except httpx.RequestError:
|
|
310
|
+
raise TransportError("HTTP request failed") from None
|
|
311
|
+
if response is None:
|
|
312
|
+
if attempt == retries:
|
|
313
|
+
raise TransportError("HTTP request failed")
|
|
314
|
+
delay = None
|
|
315
|
+
elif response.is_success:
|
|
316
|
+
try:
|
|
317
|
+
value = response.json()
|
|
318
|
+
except (UnicodeError, ValueError, RecursionError):
|
|
319
|
+
raise ProtocolError("Invalid JSON in success response") from None
|
|
320
|
+
return parse_envelope(
|
|
321
|
+
value,
|
|
322
|
+
expected,
|
|
323
|
+
self._identifier(response.headers.get("X-Request-Id")),
|
|
324
|
+
self._identifier(response.headers.get("X-Operation-Id")),
|
|
325
|
+
)
|
|
326
|
+
else:
|
|
327
|
+
error = self._error(response)
|
|
328
|
+
transient = error.status_code in _TRANSIENT_STATUSES or (
|
|
329
|
+
error.status_code == 429 and error.code in _RATE_CODES
|
|
330
|
+
)
|
|
331
|
+
delay = error.retry_after
|
|
332
|
+
if (
|
|
333
|
+
attempt == retries
|
|
334
|
+
or not transient
|
|
335
|
+
or (delay is not None and delay > _MAX_RETRY_DELAY)
|
|
336
|
+
):
|
|
337
|
+
raise error
|
|
338
|
+
time.sleep(delay if delay is not None else min(0.25 * 2**attempt, _MAX_RETRY_DELAY))
|
|
339
|
+
raise AssertionError("unreachable")
|
|
340
|
+
|
|
341
|
+
@contextmanager
|
|
342
|
+
def download(
|
|
343
|
+
self,
|
|
344
|
+
path: str,
|
|
345
|
+
*,
|
|
346
|
+
range_header: str | None = None,
|
|
347
|
+
if_match: str | None = None,
|
|
348
|
+
) -> Iterator[Download]:
|
|
349
|
+
headers = self._headers(path, False)
|
|
350
|
+
headers["Accept"] = "application/x-ndjson, application/vnd.apache.parquet"
|
|
351
|
+
headers["Accept-Encoding"] = "identity"
|
|
352
|
+
for name, value, limit in (("Range", range_header, 128), ("If-Match", if_match, 512)):
|
|
353
|
+
if value is not None:
|
|
354
|
+
if len(value) > limit or not re.fullmatch(r"[ -~]+", value):
|
|
355
|
+
raise ValueError(f"Invalid {name} header")
|
|
356
|
+
headers[name] = value
|
|
357
|
+
try:
|
|
358
|
+
request = self._client.build_request("GET", path, headers=headers)
|
|
359
|
+
response = self._client.send(request, stream=True)
|
|
360
|
+
except httpx.RequestError:
|
|
361
|
+
raise TransportError("Export request failed") from None
|
|
362
|
+
try:
|
|
363
|
+
if response.status_code not in (200, 206):
|
|
364
|
+
try:
|
|
365
|
+
response.read()
|
|
366
|
+
except httpx.RequestError:
|
|
367
|
+
raise TransportError("Export response could not be read") from None
|
|
368
|
+
raise self._error(response)
|
|
369
|
+
media_type = response.headers.get("Content-Type", "").partition(";")[0].strip().lower()
|
|
370
|
+
if media_type not in {"application/x-ndjson", "application/vnd.apache.parquet"}:
|
|
371
|
+
raise ProtocolError("Unexpected export content type")
|
|
372
|
+
_validate_export_range(range_header, response)
|
|
373
|
+
yield Download(response)
|
|
374
|
+
finally:
|
|
375
|
+
response.close()
|
datafortennis/_types.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Types shared across SDK resources. JSON strings and nulls retain their wire types."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Generic, Literal, TypeAlias, TypeVar
|
|
8
|
+
|
|
9
|
+
from .errors import ProtocolError
|
|
10
|
+
|
|
11
|
+
JsonValue: TypeAlias = None | bool | int | float | str | list["JsonValue"] | dict[str, "JsonValue"]
|
|
12
|
+
JsonObject: TypeAlias = dict[str, JsonValue]
|
|
13
|
+
Query: TypeAlias = Mapping[str, str | int | float | bool | None]
|
|
14
|
+
Shape: TypeAlias = Literal["object", "list", "either"]
|
|
15
|
+
T = TypeVar("T")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class Page:
|
|
20
|
+
limit: int
|
|
21
|
+
next_cursor: str | None = field(repr=False)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class Response(Generic[T]):
|
|
26
|
+
data: T = field(repr=False)
|
|
27
|
+
meta: JsonObject | None = field(repr=False)
|
|
28
|
+
page: Page | None
|
|
29
|
+
request_id: str | None = None
|
|
30
|
+
operation_id: str | None = None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def parse_envelope(
|
|
34
|
+
value: object,
|
|
35
|
+
expected: Shape,
|
|
36
|
+
request_id: str | None,
|
|
37
|
+
operation_id: str | None,
|
|
38
|
+
) -> Response[JsonObject | list[JsonObject]]:
|
|
39
|
+
required = {"data", "meta", "page", "error"}
|
|
40
|
+
if not isinstance(value, dict) or not required.issubset(value) or value["error"] is not None:
|
|
41
|
+
raise ProtocolError("Invalid API success envelope")
|
|
42
|
+
data, meta, page = value["data"], value["meta"], value["page"]
|
|
43
|
+
if isinstance(data, list):
|
|
44
|
+
if expected == "object" or not all(isinstance(item, dict) for item in data):
|
|
45
|
+
raise ProtocolError("Unexpected data shape")
|
|
46
|
+
elif not isinstance(data, dict) or expected == "list":
|
|
47
|
+
raise ProtocolError("Unexpected data shape")
|
|
48
|
+
if meta is not None and not isinstance(meta, dict):
|
|
49
|
+
raise ProtocolError("Invalid response metadata")
|
|
50
|
+
|
|
51
|
+
paging = None
|
|
52
|
+
if page is not None:
|
|
53
|
+
if not isinstance(page, dict) or not {"limit", "next_cursor"}.issubset(page):
|
|
54
|
+
raise ProtocolError("Invalid page metadata")
|
|
55
|
+
limit, cursor = page["limit"], page["next_cursor"]
|
|
56
|
+
if (
|
|
57
|
+
type(limit) is not int
|
|
58
|
+
or limit <= 0
|
|
59
|
+
or (cursor is not None and not isinstance(cursor, str))
|
|
60
|
+
):
|
|
61
|
+
raise ProtocolError("Invalid page limit or cursor")
|
|
62
|
+
paging = Page(limit, cursor)
|
|
63
|
+
return Response(data, meta, paging, request_id, operation_id)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
datafortennis/client.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Synchronous DataForTennis API client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TypeVar
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from ._transport import DEFAULT_BASE_URL, Transport
|
|
10
|
+
from .resources.catalogue import (
|
|
11
|
+
Datasets,
|
|
12
|
+
Draws,
|
|
13
|
+
Editions,
|
|
14
|
+
Players,
|
|
15
|
+
Releases,
|
|
16
|
+
Tournaments,
|
|
17
|
+
)
|
|
18
|
+
from .resources.exports import Exports
|
|
19
|
+
from .resources.free import Free
|
|
20
|
+
from .resources.live import Live, Predictions
|
|
21
|
+
from .resources.matches import CoverageResource, Matches
|
|
22
|
+
from .resources.research import Research
|
|
23
|
+
|
|
24
|
+
_ClientT = TypeVar("_ClientT", bound="DataForTennis")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class DataForTennis:
|
|
28
|
+
"""Reuse one client across related calls. Close it or use a with block."""
|
|
29
|
+
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
api_key: str | None = None,
|
|
33
|
+
*,
|
|
34
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
35
|
+
timeout: float | httpx.Timeout = 10.0,
|
|
36
|
+
max_retries: int = 2,
|
|
37
|
+
transport: httpx.BaseTransport | None = None,
|
|
38
|
+
) -> None:
|
|
39
|
+
self._transport = Transport(
|
|
40
|
+
api_key,
|
|
41
|
+
base_url=base_url,
|
|
42
|
+
timeout=timeout,
|
|
43
|
+
max_retries=max_retries,
|
|
44
|
+
transport=transport,
|
|
45
|
+
)
|
|
46
|
+
self.free = Free(self._transport)
|
|
47
|
+
self.releases = Releases(self._transport)
|
|
48
|
+
self.datasets = Datasets(self._transport)
|
|
49
|
+
self.players = Players(self._transport)
|
|
50
|
+
self.tournaments = Tournaments(self._transport)
|
|
51
|
+
self.editions = Editions(self._transport)
|
|
52
|
+
self.draws = Draws(self._transport)
|
|
53
|
+
self.matches = Matches(self._transport)
|
|
54
|
+
self.coverage = CoverageResource(self._transport)
|
|
55
|
+
self.research = Research(self._transport)
|
|
56
|
+
self.exports = Exports(self._transport)
|
|
57
|
+
self.predictions = Predictions(self._transport)
|
|
58
|
+
self.live = Live(self._transport)
|
|
59
|
+
|
|
60
|
+
def close(self) -> None:
|
|
61
|
+
self._transport.close()
|
|
62
|
+
|
|
63
|
+
def __enter__(self: _ClientT) -> _ClientT: # noqa: PYI019 - Python 3.10 has no typing.Self
|
|
64
|
+
self._transport.__enter__()
|
|
65
|
+
return self
|
|
66
|
+
|
|
67
|
+
def __exit__(self, *exc: object) -> None:
|
|
68
|
+
self.close()
|
datafortennis/errors.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Public exceptions. Server messages, URLs and request objects are omitted."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Literal
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class DataForTennisError(Exception):
|
|
8
|
+
"""Base class for API, transport, and response format failures."""
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class TransportError(DataForTennisError):
|
|
12
|
+
"""The request could not be completed."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ProtocolError(DataForTennisError):
|
|
16
|
+
"""A successful response did not match the endpoint's response format."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class APIError(DataForTennisError):
|
|
20
|
+
"""A rejected request with sanitized fields from the API."""
|
|
21
|
+
|
|
22
|
+
def __init__(
|
|
23
|
+
self,
|
|
24
|
+
status_code: int,
|
|
25
|
+
code: str,
|
|
26
|
+
*,
|
|
27
|
+
request_id: str | None = None,
|
|
28
|
+
retry_after: float | None = None,
|
|
29
|
+
content_range: str | None = None,
|
|
30
|
+
) -> None:
|
|
31
|
+
self.status_code = status_code
|
|
32
|
+
self.code = code
|
|
33
|
+
self.request_id = request_id
|
|
34
|
+
self.retry_after = retry_after
|
|
35
|
+
self.content_range = content_range
|
|
36
|
+
description = f"HTTP {status_code} ({code})"
|
|
37
|
+
if request_id:
|
|
38
|
+
description += f", request ID {request_id}"
|
|
39
|
+
super().__init__(description)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class AuthenticationError(APIError):
|
|
43
|
+
"""The credential was missing or rejected."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class AuthorizationError(APIError):
|
|
47
|
+
"""The credential lacks the required scope, plan, or release."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class NotFoundError(APIError):
|
|
51
|
+
"""The requested resource was not found."""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class ConflictError(APIError):
|
|
55
|
+
"""The request conflicts with the server's current state."""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True)
|
|
59
|
+
class IdentityCandidate:
|
|
60
|
+
index: int
|
|
61
|
+
status: Literal["resolved", "unresolved", "ambiguous"]
|
|
62
|
+
own_ids: tuple[str, ...]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class AmbiguousIdentityError(ConflictError):
|
|
66
|
+
"""Refine the input using the server's own resource IDs at each input index."""
|
|
67
|
+
|
|
68
|
+
def __init__(
|
|
69
|
+
self,
|
|
70
|
+
results: tuple[IdentityCandidate, ...],
|
|
71
|
+
*,
|
|
72
|
+
request_id: str | None,
|
|
73
|
+
) -> None:
|
|
74
|
+
super().__init__(409, "AMBIGUOUS_IDENTITY", request_id=request_id)
|
|
75
|
+
self.results = results
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class RateLimitError(APIError):
|
|
79
|
+
"""The service rejected the request due to a limit."""
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class QuotaExceededError(RateLimitError):
|
|
83
|
+
"""The period allowance or credential quota has been exhausted."""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class ServerError(APIError):
|
|
87
|
+
"""The server failed to complete the request."""
|