-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresource_accessor.py
More file actions
210 lines (183 loc) · 7.28 KB
/
Copy pathresource_accessor.py
File metadata and controls
210 lines (183 loc) · 7.28 KB
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
from mpt_api_client.constants import APPLICATION_JSON
from mpt_api_client.http.async_client import AsyncHTTPClient
from mpt_api_client.http.client import HTTPClient
from mpt_api_client.http.query_options import QueryOptions
from mpt_api_client.http.types import QueryParam, Response
from mpt_api_client.http.url_utils import join_url_path
from mpt_api_client.models.model import Model, ResourceData # NOSONAR
from mpt_api_client.models.model_collection import ModelCollection, ResourceList
_JsonPayload = ResourceData | ResourceList | None
class ResourceAccessor[ResourceModel: Model]: # NOSONAR
"""Synchronous accessor bound to a single resource URL.
Provides ``.get()``, ``.post()``, ``.put()``, ``.delete()`` helpers that
deserialize the response into a ``Model``, and a ``.do_request()`` escape
hatch that returns the raw ``Response``.
"""
def __init__(
self,
http_client: HTTPClient,
resource_url: str,
model_class: type[ResourceModel],
) -> None:
self._http_client = http_client
self._resource_url = resource_url
self._model_class = model_class
# -- raw request ---------------------------------------------------------
def do_request( # noqa: WPS211
self,
method: str,
action: str | None = None,
*,
json: _JsonPayload = None,
query_params: QueryParam | None = None,
headers: dict[str, str] | None = None,
options: QueryOptions | None = None,
) -> Response:
"""Perform an HTTP request and return the raw ``Response``.
Args:
method: HTTP method (GET, POST, PUT, DELETE …).
action: Optional sub-path appended after the resource id.
json: JSON body payload.
query_params: Query-string parameters.
headers: Extra HTTP headers.
options: Query options.
"""
url = join_url_path(self._resource_url, action) if action else self._resource_url
return self._http_client.request(
method, url, json=json, query_params=query_params, headers=headers, options=options
)
# -- model-returning helpers ---------------------------------------------
def get(
self,
action: str | None = None,
*,
query_params: QueryParam | None = None,
options: QueryOptions | None = None,
) -> ResourceModel:
"""``GET`` the resource (optionally with a sub-action)."""
return self._action("GET", action, query_params=query_params, options=options) # type: ignore[return-value]
def post(
self,
action: str | None = None,
*,
json: _JsonPayload = None,
query_params: QueryParam | None = None,
) -> ResourceModel:
"""``POST`` to the resource (optionally with a sub-action)."""
return self._action("POST", action, json=json, query_params=query_params) # type: ignore[return-value]
def put(
self,
action: str | None = None,
*,
json: _JsonPayload = None,
query_params: QueryParam | None = None,
) -> ResourceModel:
"""``PUT`` to the resource (optionally with a sub-action)."""
return self._action("PUT", action, json=json, query_params=query_params) # type: ignore[return-value]
def delete(self) -> None:
"""``DELETE`` the resource."""
self.do_request("DELETE")
def _action(
self,
method: str,
action: str | None = None,
*,
json: _JsonPayload = None,
query_params: QueryParam | None = None,
options: QueryOptions | None = None,
) -> ResourceModel | ModelCollection[ResourceModel]:
response = self.do_request(
method,
action,
json=json,
query_params=query_params,
headers={"Accept": APPLICATION_JSON},
options=options,
)
return self._model_class.from_response(response)
class AsyncResourceAccessor[ResourceModel: Model]: # NOSONAR
"""Asynchronous accessor bound to a single resource URL.
Async counterpart of :class:`ResourceAccessor`.
"""
def __init__(
self,
http_client: AsyncHTTPClient,
resource_url: str,
model_class: type[ResourceModel],
) -> None:
self._http_client = http_client
self._resource_url = resource_url
self._model_class = model_class
# -- raw request ---------------------------------------------------------
async def do_request( # noqa: WPS211
self,
method: str,
action: str | None = None,
*,
json: _JsonPayload = None,
query_params: QueryParam | None = None,
headers: dict[str, str] | None = None,
options: QueryOptions | None = None,
) -> Response:
"""Perform an HTTP request and return the raw ``Response``.
Args:
method: HTTP method (GET, POST, PUT, DELETE …).
action: Optional sub-path appended after the resource id.
json: JSON body payload.
query_params: Query-string parameters.
headers: Extra HTTP headers.
options: Additional options for the request.
"""
url = join_url_path(self._resource_url, action) if action else self._resource_url
return await self._http_client.request(
method, url, json=json, query_params=query_params, headers=headers, options=options
)
# -- model-returning helpers ---------------------------------------------
async def get(
self,
action: str | None = None,
*,
query_params: QueryParam | None = None,
options: QueryOptions | None = None,
) -> ResourceModel:
"""``GET`` the resource (optionally with a sub-action)."""
return await self._action("GET", action, query_params=query_params, options=options) # type: ignore[return-value]
async def post(
self,
action: str | None = None,
*,
json: _JsonPayload = None,
query_params: QueryParam | None = None,
) -> ResourceModel:
"""``POST`` to the resource (optionally with a sub-action)."""
return await self._action("POST", action, json=json, query_params=query_params) # type: ignore[return-value]
async def put(
self,
action: str | None = None,
*,
json: _JsonPayload = None,
query_params: QueryParam | None = None,
) -> ResourceModel:
"""``PUT`` to the resource (optionally with a sub-action)."""
return await self._action("PUT", action, json=json, query_params=query_params) # type: ignore[return-value]
async def delete(self) -> None:
"""``DELETE`` the resource."""
await self.do_request("DELETE")
async def _action(
self,
method: str,
action: str | None = None,
*,
json: _JsonPayload = None,
query_params: QueryParam | None = None,
options: QueryOptions | None = None,
) -> ResourceModel | ModelCollection[ResourceModel]:
response = await self.do_request(
method,
action,
json=json,
query_params=query_params,
headers={"Accept": APPLICATION_JSON},
options=options,
)
return self._model_class.from_response(response)