spec2py-runtime 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.
- spec2py_runtime/__init__.py +151 -0
- spec2py_runtime/_auth.py +180 -0
- spec2py_runtime/_client.py +809 -0
- spec2py_runtime/_exceptions.py +193 -0
- spec2py_runtime/_files.py +79 -0
- spec2py_runtime/_models.py +260 -0
- spec2py_runtime/_pagination.py +293 -0
- spec2py_runtime/_qs.py +92 -0
- spec2py_runtime/_response.py +98 -0
- spec2py_runtime/_retry.py +77 -0
- spec2py_runtime/_streaming.py +245 -0
- spec2py_runtime/_types.py +71 -0
- spec2py_runtime/_version.py +24 -0
- spec2py_runtime/py.typed +0 -0
- spec2py_runtime-0.1.0.dist-info/METADATA +56 -0
- spec2py_runtime-0.1.0.dist-info/RECORD +18 -0
- spec2py_runtime-0.1.0.dist-info/WHEEL +4 -0
- spec2py_runtime-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""Runtime for spec2py-generated API clients.
|
|
2
|
+
|
|
3
|
+
Generated packages import from here; end users mostly touch the error classes,
|
|
4
|
+
``NOT_GIVEN``, the auth helpers and ``Hooks``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from ._auth import ApiKeyAuth, BasicAuth, BearerAuth, MultiAuth, OAuth2ClientCredentials
|
|
8
|
+
from ._client import (
|
|
9
|
+
DEFAULT_MAX_RETRIES,
|
|
10
|
+
DEFAULT_TIMEOUT,
|
|
11
|
+
APIClient,
|
|
12
|
+
APIResource,
|
|
13
|
+
AsyncAPIClient,
|
|
14
|
+
AsyncAPIResource,
|
|
15
|
+
Hooks,
|
|
16
|
+
RequestOptions,
|
|
17
|
+
RequestSpec,
|
|
18
|
+
__version__,
|
|
19
|
+
)
|
|
20
|
+
from ._exceptions import (
|
|
21
|
+
APIConnectionError,
|
|
22
|
+
APIError,
|
|
23
|
+
APIResponseValidationError,
|
|
24
|
+
APIStatusError,
|
|
25
|
+
APITimeoutError,
|
|
26
|
+
AuthenticationError,
|
|
27
|
+
BadRequestError,
|
|
28
|
+
ConflictError,
|
|
29
|
+
InternalServerError,
|
|
30
|
+
NotFoundError,
|
|
31
|
+
PaginationOriginError,
|
|
32
|
+
PermissionDeniedError,
|
|
33
|
+
RateLimitError,
|
|
34
|
+
UnprocessableEntityError,
|
|
35
|
+
)
|
|
36
|
+
from ._models import (
|
|
37
|
+
BaseModel,
|
|
38
|
+
Tolerant,
|
|
39
|
+
build_body,
|
|
40
|
+
jsonable,
|
|
41
|
+
link_models,
|
|
42
|
+
parse_value,
|
|
43
|
+
validate_param,
|
|
44
|
+
)
|
|
45
|
+
from ._pagination import (
|
|
46
|
+
AsyncPage,
|
|
47
|
+
AsyncPaginator,
|
|
48
|
+
CursorPagination,
|
|
49
|
+
LinkHeaderPagination,
|
|
50
|
+
NextPage,
|
|
51
|
+
OffsetPagination,
|
|
52
|
+
Page,
|
|
53
|
+
PageNumberPagination,
|
|
54
|
+
PageState,
|
|
55
|
+
PaginationStrategy,
|
|
56
|
+
)
|
|
57
|
+
from ._qs import path_template
|
|
58
|
+
from ._response import (
|
|
59
|
+
APIResponse,
|
|
60
|
+
async_to_raw_response_wrapper,
|
|
61
|
+
to_raw_response_wrapper,
|
|
62
|
+
)
|
|
63
|
+
from ._retry import RetryPolicy
|
|
64
|
+
from ._streaming import (
|
|
65
|
+
AsyncStream,
|
|
66
|
+
AsyncStreamManager,
|
|
67
|
+
ServerSentEvent,
|
|
68
|
+
SSEDecoder,
|
|
69
|
+
Stream,
|
|
70
|
+
StreamManager,
|
|
71
|
+
)
|
|
72
|
+
from ._types import (
|
|
73
|
+
NOT_GIVEN,
|
|
74
|
+
Body,
|
|
75
|
+
FileTypes,
|
|
76
|
+
Headers,
|
|
77
|
+
NotGiven,
|
|
78
|
+
Query,
|
|
79
|
+
Timeout,
|
|
80
|
+
TimeoutTypes,
|
|
81
|
+
is_given,
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
__all__ = [
|
|
85
|
+
"DEFAULT_MAX_RETRIES",
|
|
86
|
+
"DEFAULT_TIMEOUT",
|
|
87
|
+
"NOT_GIVEN",
|
|
88
|
+
"APIClient",
|
|
89
|
+
"APIConnectionError",
|
|
90
|
+
"APIError",
|
|
91
|
+
"APIResource",
|
|
92
|
+
"APIResponse",
|
|
93
|
+
"APIResponseValidationError",
|
|
94
|
+
"APIStatusError",
|
|
95
|
+
"APITimeoutError",
|
|
96
|
+
"ApiKeyAuth",
|
|
97
|
+
"AsyncAPIClient",
|
|
98
|
+
"AsyncAPIResource",
|
|
99
|
+
"AsyncPage",
|
|
100
|
+
"AsyncPaginator",
|
|
101
|
+
"AsyncStream",
|
|
102
|
+
"AsyncStreamManager",
|
|
103
|
+
"AuthenticationError",
|
|
104
|
+
"BadRequestError",
|
|
105
|
+
"BaseModel",
|
|
106
|
+
"BasicAuth",
|
|
107
|
+
"BearerAuth",
|
|
108
|
+
"Body",
|
|
109
|
+
"ConflictError",
|
|
110
|
+
"CursorPagination",
|
|
111
|
+
"FileTypes",
|
|
112
|
+
"Headers",
|
|
113
|
+
"Hooks",
|
|
114
|
+
"InternalServerError",
|
|
115
|
+
"LinkHeaderPagination",
|
|
116
|
+
"MultiAuth",
|
|
117
|
+
"NextPage",
|
|
118
|
+
"NotFoundError",
|
|
119
|
+
"NotGiven",
|
|
120
|
+
"OAuth2ClientCredentials",
|
|
121
|
+
"OffsetPagination",
|
|
122
|
+
"Page",
|
|
123
|
+
"PageNumberPagination",
|
|
124
|
+
"PageState",
|
|
125
|
+
"PaginationOriginError",
|
|
126
|
+
"PaginationStrategy",
|
|
127
|
+
"PermissionDeniedError",
|
|
128
|
+
"Query",
|
|
129
|
+
"RateLimitError",
|
|
130
|
+
"RequestOptions",
|
|
131
|
+
"RequestSpec",
|
|
132
|
+
"RetryPolicy",
|
|
133
|
+
"SSEDecoder",
|
|
134
|
+
"ServerSentEvent",
|
|
135
|
+
"Stream",
|
|
136
|
+
"StreamManager",
|
|
137
|
+
"Timeout",
|
|
138
|
+
"TimeoutTypes",
|
|
139
|
+
"Tolerant",
|
|
140
|
+
"UnprocessableEntityError",
|
|
141
|
+
"__version__",
|
|
142
|
+
"async_to_raw_response_wrapper",
|
|
143
|
+
"build_body",
|
|
144
|
+
"is_given",
|
|
145
|
+
"jsonable",
|
|
146
|
+
"link_models",
|
|
147
|
+
"parse_value",
|
|
148
|
+
"path_template",
|
|
149
|
+
"to_raw_response_wrapper",
|
|
150
|
+
"validate_param",
|
|
151
|
+
]
|
spec2py_runtime/_auth.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Authentication schemes as ``httpx2.Auth`` flows.
|
|
2
|
+
|
|
3
|
+
Every scheme here works for both the sync and async clients, because httpx2
|
|
4
|
+
drives the same generator-based ``auth_flow`` in both modes. Custom auth is any
|
|
5
|
+
``httpx2.Auth`` subclass passed as ``auth=`` to a generated client.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import base64
|
|
9
|
+
import time
|
|
10
|
+
from collections.abc import Generator, Sequence
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from typing import Literal, override
|
|
13
|
+
|
|
14
|
+
import httpx2
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"ApiKeyAuth",
|
|
18
|
+
"BasicAuth",
|
|
19
|
+
"BearerAuth",
|
|
20
|
+
"MultiAuth",
|
|
21
|
+
"OAuth2ClientCredentials",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
type AuthFlow = Generator[httpx2.Request, httpx2.Response]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ApiKeyAuth(httpx2.Auth):
|
|
28
|
+
"""An API key sent in a header, query parameter or cookie."""
|
|
29
|
+
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
key: str,
|
|
33
|
+
*,
|
|
34
|
+
name: str,
|
|
35
|
+
location: Literal["header", "query", "cookie"] = "header",
|
|
36
|
+
prefix: str | None = None,
|
|
37
|
+
) -> None:
|
|
38
|
+
self.key = key
|
|
39
|
+
self.name = name
|
|
40
|
+
self.location = location
|
|
41
|
+
self.prefix = prefix
|
|
42
|
+
|
|
43
|
+
@override
|
|
44
|
+
def auth_flow(self, request: httpx2.Request) -> AuthFlow:
|
|
45
|
+
value = f"{self.prefix} {self.key}" if self.prefix else self.key
|
|
46
|
+
match self.location:
|
|
47
|
+
case "header":
|
|
48
|
+
request.headers[self.name] = value
|
|
49
|
+
case "query":
|
|
50
|
+
request.url = request.url.copy_merge_params({self.name: value})
|
|
51
|
+
case "cookie":
|
|
52
|
+
existing = request.headers.get("cookie")
|
|
53
|
+
pair = f"{self.name}={value}"
|
|
54
|
+
request.headers["cookie"] = f"{existing}; {pair}" if existing else pair
|
|
55
|
+
case _:
|
|
56
|
+
raise ValueError(f"unknown API key location {self.location!r}")
|
|
57
|
+
yield request
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class BearerAuth(httpx2.Auth):
|
|
61
|
+
"""``Authorization: Bearer <token>``."""
|
|
62
|
+
|
|
63
|
+
def __init__(self, token: str) -> None:
|
|
64
|
+
self.token = token
|
|
65
|
+
|
|
66
|
+
@override
|
|
67
|
+
def auth_flow(self, request: httpx2.Request) -> AuthFlow:
|
|
68
|
+
request.headers["Authorization"] = f"Bearer {self.token}"
|
|
69
|
+
yield request
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class BasicAuth(httpx2.Auth):
|
|
73
|
+
"""HTTP basic auth."""
|
|
74
|
+
|
|
75
|
+
def __init__(self, username: str, password: str) -> None:
|
|
76
|
+
raw = f"{username}:{password}".encode()
|
|
77
|
+
self._header = "Basic " + base64.b64encode(raw).decode("ascii")
|
|
78
|
+
|
|
79
|
+
@override
|
|
80
|
+
def auth_flow(self, request: httpx2.Request) -> AuthFlow:
|
|
81
|
+
request.headers["Authorization"] = self._header
|
|
82
|
+
yield request
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class MultiAuth(httpx2.Auth):
|
|
86
|
+
"""Apply several schemes to every request, e.g. an API key plus a bearer token."""
|
|
87
|
+
|
|
88
|
+
def __init__(self, auths: Sequence[httpx2.Auth]) -> None:
|
|
89
|
+
self.auths = list(auths)
|
|
90
|
+
|
|
91
|
+
@override
|
|
92
|
+
def auth_flow(self, request: httpx2.Request) -> AuthFlow:
|
|
93
|
+
yield from self._chain(0, request)
|
|
94
|
+
|
|
95
|
+
def _chain(
|
|
96
|
+
self, index: int, request: httpx2.Request
|
|
97
|
+
) -> Generator[httpx2.Request, httpx2.Response, httpx2.Response]:
|
|
98
|
+
if index == len(self.auths):
|
|
99
|
+
return (yield request)
|
|
100
|
+
flow = self.auths[index].auth_flow(request)
|
|
101
|
+
outgoing = next(flow)
|
|
102
|
+
while True:
|
|
103
|
+
if outgoing is request:
|
|
104
|
+
response = yield from self._chain(index + 1, outgoing)
|
|
105
|
+
else:
|
|
106
|
+
# A side request of this scheme (e.g. an OAuth2 token fetch):
|
|
107
|
+
# send it as-is, without the other schemes' credentials.
|
|
108
|
+
response = yield outgoing
|
|
109
|
+
try:
|
|
110
|
+
outgoing = flow.send(response)
|
|
111
|
+
except StopIteration:
|
|
112
|
+
return response
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@dataclass(slots=True)
|
|
116
|
+
class _Token:
|
|
117
|
+
access_token: str
|
|
118
|
+
expires_at: float | None
|
|
119
|
+
refresh_token: str | None = None
|
|
120
|
+
|
|
121
|
+
def valid(self, leeway: float) -> bool:
|
|
122
|
+
return self.expires_at is None or time.time() < self.expires_at - leeway
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@dataclass
|
|
126
|
+
class OAuth2ClientCredentials(httpx2.Auth):
|
|
127
|
+
"""OAuth2 client-credentials grant with automatic token fetch and refresh.
|
|
128
|
+
|
|
129
|
+
Fetches a token on first use, reuses it until shortly before it expires,
|
|
130
|
+
uses the refresh token when the server issued one, and retries once with a
|
|
131
|
+
fresh token if the API answers 401.
|
|
132
|
+
"""
|
|
133
|
+
|
|
134
|
+
token_url: str
|
|
135
|
+
client_id: str
|
|
136
|
+
client_secret: str
|
|
137
|
+
scopes: Sequence[str] = ()
|
|
138
|
+
audience: str | None = None
|
|
139
|
+
leeway: float = 30.0
|
|
140
|
+
requires_response_body = True
|
|
141
|
+
_token: _Token | None = field(default=None, init=False, repr=False)
|
|
142
|
+
|
|
143
|
+
def _token_request(self) -> httpx2.Request:
|
|
144
|
+
data = {
|
|
145
|
+
"grant_type": "client_credentials",
|
|
146
|
+
"client_id": self.client_id,
|
|
147
|
+
"client_secret": self.client_secret,
|
|
148
|
+
}
|
|
149
|
+
if self._token and self._token.refresh_token:
|
|
150
|
+
data["grant_type"] = "refresh_token"
|
|
151
|
+
data["refresh_token"] = self._token.refresh_token
|
|
152
|
+
if self.scopes:
|
|
153
|
+
data["scope"] = " ".join(self.scopes)
|
|
154
|
+
if self.audience:
|
|
155
|
+
data["audience"] = self.audience
|
|
156
|
+
return httpx2.Request("POST", self.token_url, data=data)
|
|
157
|
+
|
|
158
|
+
def _store(self, response: httpx2.Response) -> _Token:
|
|
159
|
+
response.raise_for_status()
|
|
160
|
+
payload = response.json()
|
|
161
|
+
expires_in = payload.get("expires_in")
|
|
162
|
+
self._token = _Token(
|
|
163
|
+
access_token=payload["access_token"],
|
|
164
|
+
expires_at=time.time() + float(expires_in) if expires_in else None,
|
|
165
|
+
refresh_token=payload.get("refresh_token"),
|
|
166
|
+
)
|
|
167
|
+
return self._token
|
|
168
|
+
|
|
169
|
+
@override
|
|
170
|
+
def auth_flow(self, request: httpx2.Request) -> AuthFlow:
|
|
171
|
+
token = self._token
|
|
172
|
+
if token is None or not token.valid(self.leeway):
|
|
173
|
+
token = self._store((yield self._token_request()))
|
|
174
|
+
request.headers["Authorization"] = f"Bearer {token.access_token}"
|
|
175
|
+
response = yield request
|
|
176
|
+
if response.status_code == 401:
|
|
177
|
+
self._token = None
|
|
178
|
+
token = self._store((yield self._token_request()))
|
|
179
|
+
request.headers["Authorization"] = f"Bearer {token.access_token}"
|
|
180
|
+
yield request
|