-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
341 lines (300 loc) · 11.6 KB
/
Copy pathclient.py
File metadata and controls
341 lines (300 loc) · 11.6 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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import abc
import json
from collections.abc import Callable
from typing import Any
import requests # type: ignore
from . import constants, entities, namedtuples
from .constants import endpoints, errors, headers
from .utils import headers as headers_utils
class BaseRequest(abc.ABC):
def do_delete(self, url: str, headers: dict[str, str]) -> Any:
return self._do_request(endpoints.DELETE_METHOD, url, headers=headers)
def do_get(self, url: str, params: dict[str, Any], headers: dict[str, str]) -> Any:
return self._do_request(
endpoints.GET_METHOD, url, params=params, headers=headers
)
def do_post(
self,
url: str,
data: dict[str, Any],
headers: dict[str, str],
as_json: bool = True,
) -> Any:
if as_json:
data = json.dumps(data) # type: ignore
return self._do_request(endpoints.POST_METHOD, url, data=data, headers=headers)
def do_put(self, url: str, data: dict[str, Any], headers: dict[str, str]) -> Any:
payload = json.loads(json.dumps(data, default=str))
return self._do_request(
endpoints.PUT_METHOD, url, json=payload, headers=headers
)
def _do_request(self, method_name: str, url: str, **kwargs: Any) -> Any:
kwargs.setdefault("timeout", constants.REQUEST_TIMEOUT)
try:
response = getattr(requests, method_name.lower())(url, **kwargs)
except requests.Timeout as exc:
error_class = self.get_error_class()
raise error_class(
f"Due to timeout error, {method_name.upper()} can't be done."
) from exc
try:
response.raise_for_status()
except requests.HTTPError as exc:
error_message = self._build_error_message(method_name, response)
raise self.get_error_class()(error_message) from exc
return json.loads(response.content) if response.content else None
def _build_error_message(
self, method_name: str, response: requests.Response
) -> str:
"""
Constrói uma mensagem de erro detalhada a partir da resposta HTTP.
Tenta extrair o conteúdo JSON da resposta quando possível, mas trata
adequadamente casos onde a resposta não é um JSON válido (como erros
504 Gateway Timeout que retornam páginas HTML ou respostas vazias).
Args:
method_name: Nome do método HTTP (GET, POST, PUT, DELETE)
response: Objeto Response do requests
Returns:
String formatada com informações do erro
"""
content = self._extract_response_content(response)
return (
f"Error while trying to do a {method_name.upper()} request.\n"
f"Status code: {response.status_code}\n"
f"Response:\n{content}"
)
def _extract_response_content(self, response: requests.Response) -> str:
"""
Extrai o conteúdo da resposta HTTP de forma segura.
Tenta primeiro parsear como JSON (para APIs que retornam erros estruturados),
mas faz fallback para texto bruto em caso de falha no parsing.
Args:
response: Objeto Response do requests
Returns:
Conteúdo da resposta formatado como string
"""
try:
return json.dumps(response.json(), ensure_ascii=False, indent=4)
except (ValueError, requests.exceptions.JSONDecodeError):
return response.text or "<empty response body>"
@abc.abstractmethod
def get_error_class(self) -> Any:
pass
class ApiClient(BaseRequest):
class Error(Exception):
pass
def __init__(
self,
domain: str = constants.BASE_URL,
origem_unidade: Any = None,
cod_unidade_autorizadora: Any = None,
):
self.domain = domain
self.origem_unidade = origem_unidade
self.cod_unidade_autorizadora = cod_unidade_autorizadora
self._token: dict[str, str] = {}
@property
def default_headers(self) -> dict[str, str]:
return headers_utils.create_headers_with(
[
headers.CONTENT_TYPE_JSON_HEADER,
headers_utils.authorization_header_factory(**self.token),
headers_utils.header_item_factory(
headers.USER_AGENT_HEADER,
system_name=constants.SOURCE_SYSTEM_NAME,
system_version=constants.SOURCE_SYSTEM_VERSION,
system_url=constants.SOURCE_SYSTEM_ABOUT_URL,
),
],
)
@property
def token(self) -> dict[str, str]:
if not self._token:
self._token = self.get_token()
return self._token
def get_token(self) -> Any:
payload = {
"username": constants.API_USERNAME,
"password": constants.API_PASSWORD,
}
return self.do_post(
self.token_endpoint,
payload,
headers_utils.create_headers_with(
[headers.CONTENT_TYPE_FORM_URLENCODED_HEADER]
),
as_json=False,
)
@property
def token_endpoint(self) -> str:
return self.get_endpoint(endpoints.TOKEN_ENDPOINT)
def get_endpoint(self, endpoint: namedtuples.Endpoint, **kwargs: Any) -> str:
base_path = self._get_endpoint_path(endpoint)
try:
path = base_path.format(**kwargs)
except KeyError as exc:
raise self.get_error_class()("Endpoint malformed") from exc
return f"{self.domain}{path}"
def _get_endpoint_path(self, endpoint: namedtuples.Endpoint) -> Any:
try:
return endpoints.ENDPOINTS[endpoint.name].path
except (AttributeError, KeyError) as exc:
error_class = self.get_error_class()
raise error_class("Endpoint not defined") from exc
def get_error_class(self) -> Any:
return self.Error
@property
def users_endpoint(self) -> str:
return self.get_endpoint(endpoints.USERS_ENDPOINT)
def user_endpoint(self, email: str) -> str:
return self.get_endpoint(endpoints.USER_ENDPOINT, email=email)
def plano_entregas_endpoint(
self,
id_plano_entregas: str,
origem_unidade: str = "",
cod_unidade_autorizadora: int = 0,
) -> str:
if not origem_unidade:
origem_unidade = self.origem_unidade
if not cod_unidade_autorizadora:
cod_unidade_autorizadora = self.cod_unidade_autorizadora
return self.get_endpoint(
endpoints.PLANO_ENTREGAS_ENDPOINT,
origem_unidade=origem_unidade,
cod_unidade_autorizadora=cod_unidade_autorizadora,
id_plano_entregas=id_plano_entregas,
)
def plano_trabalho_endpoint(
self,
id_plano_trabalho: str,
origem_unidade: str = "",
cod_unidade_autorizadora: int = 0,
) -> str:
if not origem_unidade:
origem_unidade = self.origem_unidade
if not cod_unidade_autorizadora:
cod_unidade_autorizadora = self.cod_unidade_autorizadora
return self.get_endpoint(
endpoints.PLANO_TRABALHO_ENDPOINT,
origem_unidade=origem_unidade,
cod_unidade_autorizadora=cod_unidade_autorizadora,
id_plano_trabalho=id_plano_trabalho,
)
def participante_endpoint(
self,
cod_unidade_lotacao: int,
matricula_siape: str,
origem_unidade: str = "",
cod_unidade_autorizadora: int = 0,
) -> str:
if not origem_unidade:
origem_unidade = self.origem_unidade
if not cod_unidade_autorizadora:
cod_unidade_autorizadora = self.cod_unidade_autorizadora
return self.get_endpoint(
endpoints.PARTICIPANTE_ENDPOINT,
origem_unidade=origem_unidade,
cod_unidade_autorizadora=cod_unidade_autorizadora,
cod_unidade_lotacao=cod_unidade_lotacao,
matricula_siape=matricula_siape,
)
def consultar_usuario(self, email: str) -> entities.User:
response = self.retry_on_expired_token(
lambda: self.do_get(self.user_endpoint(email), {}, self.default_headers)
)
return entities.User(**response)
def consultar_participante(
self,
cod_unidade_lotacao: int,
matricula_siape: str,
origem_unidade: str = "",
cod_unidade_autorizadora: int = 0,
) -> entities.Participante:
response = self.retry_on_expired_token(
self.do_get,
self.participante_endpoint(
cod_unidade_lotacao,
matricula_siape,
origem_unidade,
cod_unidade_autorizadora,
),
{},
self.default_headers,
)
return entities.Participante(**response)
def enviar_participante(self, participante: entities.Participante) -> Any:
return self.retry_on_expired_token(
self.do_put,
self.participante_endpoint(
participante.cod_unidade_lotacao,
participante.matricula_siape,
participante.origem_unidade,
participante.cod_unidade_autorizadora,
),
participante.to_dict(),
self.default_headers,
)
def consultar_plano_entregas(
self,
id_plano_entregas: str,
origem_unidade: str = "",
cod_unidade_autorizadora: int = 0,
) -> entities.PlanoDeEntregas:
response = self.retry_on_expired_token(
lambda: self.do_get(
self.plano_entregas_endpoint(
id_plano_entregas, origem_unidade, cod_unidade_autorizadora
),
{},
self.default_headers,
)
)
return entities.PlanoDeEntregas(**response)
def enviar_plano_entregas(self, plano_entregas: entities.PlanoDeEntregas) -> Any:
return self.retry_on_expired_token(
self.do_put,
self.plano_entregas_endpoint(
plano_entregas.id_plano_entregas,
plano_entregas.origem_unidade,
plano_entregas.cod_unidade_autorizadora,
),
plano_entregas.to_dict(),
self.default_headers,
)
def consultar_plano_trabalho(
self,
id_plano_trabalho: str,
origem_unidade: str = "",
cod_unidade_autorizadora: int = 0,
) -> entities.PlanoDeTrabalho:
response = self.retry_on_expired_token(
self.do_get,
self.plano_trabalho_endpoint(
id_plano_trabalho, origem_unidade, cod_unidade_autorizadora
),
{},
self.default_headers,
)
return entities.PlanoDeTrabalho(**response)
def enviar_plano_trabalho(self, plano_trabalho: entities.PlanoDeTrabalho) -> Any:
return self.retry_on_expired_token(
self.do_put,
self.plano_trabalho_endpoint(
plano_trabalho.id_plano_trabalho,
plano_trabalho.origem_unidade,
plano_trabalho.cod_unidade_autorizadora,
),
plano_trabalho.to_dict(),
self.default_headers,
)
def retry_on_expired_token(
self, request_call: Callable[..., Any], *args: Any, **kwargs: Any
) -> Any:
try:
response = request_call(*args, **kwargs)
except self.Error as exc:
if errors.TOKEN_INVALIDO not in str(exc):
raise exc
self._token = self.get_token()
response = request_call(*args, **kwargs)
return response