python-bcb 0.3.6__py3-none-any.whl → 0.4.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.
bcb/http.py CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import Callable, TypeVar
5
+ from typing import Any, Callable, NoReturn, TypeAlias, TypeVar
6
6
 
7
7
  import httpx
8
8
  from tenacity import (
@@ -11,20 +11,34 @@ from tenacity import (
11
11
  wait_exponential,
12
12
  )
13
13
 
14
+ from bcb.exceptions import (
15
+ BCBAPIError,
16
+ BCBAPINotFoundError,
17
+ BCBAPIServerError,
18
+ BCBRateLimitError,
19
+ )
20
+
14
21
  # Default timeout for all HTTP requests (seconds)
15
22
  DEFAULT_TIMEOUT = 30.0
16
23
 
24
+ RequestTimeout: TypeAlias = float | httpx.Timeout | None
25
+
17
26
  # Shared synchronous HTTP client
18
27
  _CLIENT = httpx.Client(
19
28
  timeout=DEFAULT_TIMEOUT,
20
29
  follow_redirects=True,
21
30
  )
22
31
 
23
- # Shared asynchronous HTTP client (for future async API)
24
- _ASYNC_CLIENT = httpx.AsyncClient(
25
- timeout=DEFAULT_TIMEOUT,
26
- follow_redirects=True,
27
- )
32
+
33
+ def _make_async_client() -> httpx.AsyncClient:
34
+ return httpx.AsyncClient(
35
+ timeout=DEFAULT_TIMEOUT,
36
+ follow_redirects=True,
37
+ )
38
+
39
+
40
+ # Shared asynchronous HTTP client
41
+ _ASYNC_CLIENT = _make_async_client()
28
42
 
29
43
 
30
44
  # Retry decorator for transient failures
@@ -55,9 +69,18 @@ def get_async_client() -> httpx.AsyncClient:
55
69
  httpx.AsyncClient
56
70
  Shared async client with connection pooling and configured timeout.
57
71
  """
72
+ global _ASYNC_CLIENT
73
+ if _ASYNC_CLIENT.is_closed:
74
+ _ASYNC_CLIENT = _make_async_client()
58
75
  return _ASYNC_CLIENT
59
76
 
60
77
 
78
+ async def aclose_async_client() -> None:
79
+ """Close the shared async client from async code."""
80
+ if not _ASYNC_CLIENT.is_closed:
81
+ await _ASYNC_CLIENT.aclose()
82
+
83
+
61
84
  def close_async_client() -> None:
62
85
  """Close the shared async client.
63
86
 
@@ -67,21 +90,84 @@ def close_async_client() -> None:
67
90
  import asyncio
68
91
 
69
92
  try:
70
- loop = asyncio.get_event_loop()
71
- if loop.is_running():
72
- # If called from async context, schedule closing
73
- asyncio.create_task(_ASYNC_CLIENT.aclose())
74
- else:
75
- # If called from sync context, run the close
76
- loop.run_until_complete(_ASYNC_CLIENT.aclose())
93
+ loop = asyncio.get_running_loop()
77
94
  except RuntimeError:
78
- # No event loop, create one
79
- asyncio.run(_ASYNC_CLIENT.aclose())
95
+ asyncio.run(aclose_async_client())
96
+ else:
97
+ loop.create_task(aclose_async_client())
98
+
99
+
100
+ def timeout_kwargs(timeout: RequestTimeout) -> dict[str, Any]:
101
+ """Build request kwargs without overriding the client default timeout."""
102
+ if timeout is None:
103
+ return {}
104
+ return {"timeout": timeout}
80
105
 
81
106
 
82
107
  T = TypeVar("T")
83
108
 
84
109
 
110
+ def _raise_error(
111
+ error_cls: type[Exception],
112
+ message: str,
113
+ status_code: int,
114
+ ) -> NoReturn:
115
+ """Raise project exceptions with or without an HTTP status constructor."""
116
+ if issubclass(error_cls, BCBAPIError):
117
+ raise error_cls(message, status_code)
118
+ raise error_cls(message)
119
+
120
+
121
+ def raise_for_status(
122
+ response: httpx.Response,
123
+ *,
124
+ context: str,
125
+ expected_status: int | tuple[int, ...] = 200,
126
+ error_cls: type[Exception] = BCBAPIError,
127
+ not_found_cls: type[Exception] = BCBAPINotFoundError,
128
+ rate_limit_cls: type[Exception] = BCBRateLimitError,
129
+ server_error_cls: type[Exception] = BCBAPIServerError,
130
+ rate_limit_message: str | None = None,
131
+ not_found_message: str | None = None,
132
+ server_error_message: str | None = None,
133
+ error_message: str | None = None,
134
+ ) -> None:
135
+ """Raise a consistent project exception for unexpected HTTP statuses."""
136
+ expected = (
137
+ (expected_status,) if isinstance(expected_status, int) else expected_status
138
+ )
139
+ status_code = response.status_code
140
+ if status_code in expected:
141
+ return
142
+
143
+ if status_code == 429:
144
+ message = (
145
+ rate_limit_message or "BCB API rate limit exceeded. Please try again later."
146
+ )
147
+ _raise_error(rate_limit_cls, message, status_code)
148
+ if status_code == 404:
149
+ message = not_found_message or f"{context} not found (status 404)"
150
+ _raise_error(not_found_cls, message, status_code)
151
+ if status_code >= 500:
152
+ message = (
153
+ server_error_message or f"{context} server error (status {status_code})"
154
+ )
155
+ _raise_error(server_error_cls, message, status_code)
156
+
157
+ message = error_message or f"{context} request failed with status {status_code}"
158
+ _raise_error(error_cls, message, status_code)
159
+
160
+
161
+ def raise_for_request_error(
162
+ exc: httpx.HTTPError,
163
+ *,
164
+ context: str,
165
+ error_cls: type[Exception] = BCBAPIError,
166
+ ) -> NoReturn:
167
+ """Raise a consistent project exception for HTTP client failures."""
168
+ _raise_error(error_cls, f"{context} request failed: {exc}", status_code=0)
169
+
170
+
85
171
  def with_retry(func: Callable[..., T]) -> Callable[..., T]:
86
172
  """Decorator to add automatic retry with exponential backoff to any function.
87
173
 
bcb/odata/api.py CHANGED
@@ -1,9 +1,12 @@
1
1
  from __future__ import annotations
2
2
 
3
- from typing import Any, Literal, Optional, Union, overload
3
+ from typing import Any, Callable, Literal, Optional, Union, overload
4
4
 
5
+ from bcb.http import RequestTimeout
6
+ from bcb.utils import Date
5
7
  from bcb.odata.framework import (
6
8
  ODataEntitySet,
9
+ ODataFilterExpression,
7
10
  ODataFunctionImport,
8
11
  ODataQuery,
9
12
  ODataPropertyFilter,
@@ -16,12 +19,28 @@ import pandas as pd
16
19
  OLINDA_BASE_URL = "https://olinda.bcb.gov.br/olinda/servico"
17
20
 
18
21
 
22
+ def _format_ptax_date_parameter(value: Any) -> Any:
23
+ try:
24
+ parsed = Date(value).date
25
+ except ValueError:
26
+ return value
27
+ return f"{parsed.month}/{parsed.day}/{parsed.year}"
28
+
29
+
30
+ PTAX_DATE_PARAMETER_FORMATTERS: dict[str, Callable[[Any], Any]] = {
31
+ "dataCotacao": _format_ptax_date_parameter,
32
+ "dataInicial": _format_ptax_date_parameter,
33
+ "dataInicialCotacao": _format_ptax_date_parameter,
34
+ "dataFinalCotacao": _format_ptax_date_parameter,
35
+ }
36
+
37
+
19
38
  class EndpointMeta(type):
20
39
  def __init__(self, *args: Any, **kwargs: Any) -> None:
21
40
  super().__init__(*args, **kwargs)
22
41
 
23
- def __call__(self, *args: Any) -> Any:
24
- obj = super().__call__(*args)
42
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
43
+ obj = super().__call__(*args, **kwargs)
25
44
  entity = args[0]
26
45
  if isinstance(entity, ODataEntitySet):
27
46
  for name, prop in entity.entity.properties.items():
@@ -49,20 +68,39 @@ class EndpointQuery(ODataQuery):
49
68
  entity: Any,
50
69
  url: str,
51
70
  date_columns: Optional[list[str]] = None,
71
+ parameter_formatters: Optional[dict[str, Callable[[Any], Any]]] = None,
72
+ *,
73
+ timeout: RequestTimeout = None,
52
74
  ) -> None:
53
- super().__init__(entity, url)
75
+ super().__init__(entity, url, timeout=timeout)
54
76
  self._date_columns: list[str] = date_columns or []
77
+ self._parameter_formatters = parameter_formatters or {}
78
+
79
+ def _format_parameter(self, parameter: Any, value: Any) -> str:
80
+ formatter = self._parameter_formatters.get(parameter.name)
81
+ if formatter is not None:
82
+ value = formatter(value)
83
+ return super()._format_parameter(parameter, value)
55
84
 
56
85
  @overload
57
- def collect(self, output: Literal["dataframe"] = ...) -> pd.DataFrame: ...
86
+ def collect(
87
+ self,
88
+ output: Literal["dataframe"] = ...,
89
+ *,
90
+ timeout: RequestTimeout = ...,
91
+ ) -> pd.DataFrame: ...
58
92
 
59
93
  @overload
60
- def collect(self, output: Literal["text"]) -> str: ...
94
+ def collect(
95
+ self, output: Literal["text"], *, timeout: RequestTimeout = ...
96
+ ) -> str: ...
61
97
 
62
- def collect(self, output: str = "dataframe") -> Union[pd.DataFrame, str]:
98
+ def collect(
99
+ self, output: str = "dataframe", *, timeout: RequestTimeout = None
100
+ ) -> Union[pd.DataFrame, str]:
63
101
  if output == "text":
64
- return self.text()
65
- raw_data = super().collect()
102
+ return self.text(timeout=timeout)
103
+ raw_data = super().collect(timeout=timeout)
66
104
  data = pd.DataFrame(raw_data["value"])
67
105
  if not self._raw:
68
106
  if self._date_columns:
@@ -85,12 +123,12 @@ class EndpointQuery(ODataQuery):
85
123
  return data
86
124
 
87
125
  async def async_collect(
88
- self, output: str = "dataframe"
126
+ self, output: str = "dataframe", *, timeout: RequestTimeout = None
89
127
  ) -> Union[pd.DataFrame, str]:
90
128
  """Async version of collect(). Awaits super().async_collect() for data fetch."""
91
129
  if output == "text":
92
- return await self.async_text()
93
- raw_data = await super().async_collect()
130
+ return await self.async_text(timeout=timeout)
131
+ raw_data = await super().async_collect(timeout=timeout)
94
132
  data = pd.DataFrame(raw_data["value"])
95
133
  if not self._raw:
96
134
  if self._date_columns:
@@ -126,7 +164,13 @@ class Endpoint(metaclass=EndpointMeta):
126
164
  """
127
165
 
128
166
  def __init__(
129
- self, entity: Any, url: str, date_columns: Optional[list[str]] = None
167
+ self,
168
+ entity: Any,
169
+ url: str,
170
+ date_columns: Optional[list[str]] = None,
171
+ parameter_formatters: Optional[dict[str, Callable[[Any], Any]]] = None,
172
+ *,
173
+ timeout: RequestTimeout = None,
130
174
  ) -> None:
131
175
  """
132
176
  Construtor da classe Endpoint.
@@ -145,16 +189,19 @@ class Endpoint(metaclass=EndpointMeta):
145
189
  self._entity = entity
146
190
  self._url = url
147
191
  self._date_columns: list[str] = date_columns or []
192
+ self._parameter_formatters = parameter_formatters or {}
193
+ self._timeout = timeout
148
194
 
149
195
  def get(
150
196
  self,
151
197
  *args: Any,
152
- filter: Optional[ODataPropertyFilter] = None,
198
+ filter: Optional[ODataFilterExpression] = None,
153
199
  orderby: Optional[ODataPropertyOrderBy] = None,
154
200
  select: Optional[ODataProperty] = None,
155
201
  limit: Optional[int] = None,
156
202
  skip: Optional[int] = None,
157
203
  output: str = "dataframe",
204
+ timeout: RequestTimeout = None,
158
205
  verbose: bool = False,
159
206
  **kwargs: Any,
160
207
  ) -> Union[pd.DataFrame, str]:
@@ -186,7 +233,13 @@ class Endpoint(metaclass=EndpointMeta):
186
233
  pd.DataFrame or str: resultado da consulta. Returns a DataFrame by
187
234
  default; returns a raw JSON string when ``output='text'``.
188
235
  """
189
- _query = EndpointQuery(self._entity, self._url, self._date_columns)
236
+ _query = EndpointQuery(
237
+ self._entity,
238
+ self._url,
239
+ self._date_columns,
240
+ self._parameter_formatters,
241
+ timeout=self._timeout,
242
+ )
190
243
 
191
244
  # Apply explicit kwargs first
192
245
  if filter is not None:
@@ -218,9 +271,9 @@ class Endpoint(metaclass=EndpointMeta):
218
271
  if verbose:
219
272
  _query.show()
220
273
  if output == "text":
221
- data = _query.collect(output="text")
274
+ data = _query.collect(output="text", timeout=timeout)
222
275
  else:
223
- data = _query.collect()
276
+ data = _query.collect(timeout=timeout)
224
277
  _query.reset()
225
278
  return data
226
279
 
@@ -232,7 +285,13 @@ class Endpoint(metaclass=EndpointMeta):
232
285
  -------
233
286
  bcb.odata.api.EndpointQuery
234
287
  """
235
- return EndpointQuery(self._entity, self._url, self._date_columns)
288
+ return EndpointQuery(
289
+ self._entity,
290
+ self._url,
291
+ self._date_columns,
292
+ self._parameter_formatters,
293
+ timeout=self._timeout,
294
+ )
236
295
 
237
296
  def async_query(self) -> EndpointQuery:
238
297
  """
@@ -243,17 +302,24 @@ class Endpoint(metaclass=EndpointMeta):
243
302
  bcb.odata.api.EndpointQuery
244
303
  Same as query(); call async_collect() on the result
245
304
  """
246
- return EndpointQuery(self._entity, self._url, self._date_columns)
305
+ return EndpointQuery(
306
+ self._entity,
307
+ self._url,
308
+ self._date_columns,
309
+ self._parameter_formatters,
310
+ timeout=self._timeout,
311
+ )
247
312
 
248
313
  async def async_get(
249
314
  self,
250
315
  *args: Any,
251
- filter: Optional[ODataPropertyFilter] = None,
316
+ filter: Optional[ODataFilterExpression] = None,
252
317
  orderby: Optional[ODataPropertyOrderBy] = None,
253
318
  select: Optional[ODataProperty] = None,
254
319
  limit: Optional[int] = None,
255
320
  skip: Optional[int] = None,
256
321
  output: str = "dataframe",
322
+ timeout: RequestTimeout = None,
257
323
  verbose: bool = False,
258
324
  **kwargs: Any,
259
325
  ) -> Union[pd.DataFrame, str]:
@@ -287,7 +353,13 @@ class Endpoint(metaclass=EndpointMeta):
287
353
  Union[pd.DataFrame, str]
288
354
  Resultado da consulta
289
355
  """
290
- _query = EndpointQuery(self._entity, self._url, self._date_columns)
356
+ _query = EndpointQuery(
357
+ self._entity,
358
+ self._url,
359
+ self._date_columns,
360
+ self._parameter_formatters,
361
+ timeout=self._timeout,
362
+ )
291
363
 
292
364
  # Apply explicit kwargs first
293
365
  if filter is not None:
@@ -319,9 +391,9 @@ class Endpoint(metaclass=EndpointMeta):
319
391
  if verbose:
320
392
  _query.show()
321
393
  if output == "text":
322
- data = await _query.async_collect(output="text")
394
+ data = await _query.async_collect(output="text", timeout=timeout)
323
395
  else:
324
- data = await _query.async_collect()
396
+ data = await _query.async_collect(timeout=timeout)
325
397
  _query.reset()
326
398
  return data
327
399
 
@@ -335,14 +407,16 @@ class BaseODataAPI:
335
407
 
336
408
  BASE_URL: str
337
409
  DATE_COLUMNS: list[str] = []
410
+ PARAMETER_FORMATTERS: dict[str, Callable[[Any], Any]] = {}
338
411
 
339
- def __init__(self) -> None:
412
+ def __init__(self, *, timeout: RequestTimeout = None) -> None:
340
413
  """
341
414
  BaseODataAPI construtor
342
415
  """
343
- self.service = ODataService(self.BASE_URL)
416
+ self._timeout = timeout
417
+ self.service = ODataService(self.BASE_URL, timeout=timeout)
344
418
 
345
- def describe(self, endpoint: Optional[str] = None) -> None:
419
+ def describe(self, endpoint: Optional[str] = None, *, full: bool = True) -> None:
346
420
  """
347
421
  Mostra a descrição de uma API ou de um *endpoint*
348
422
  específico.
@@ -351,7 +425,12 @@ class BaseODataAPI:
351
425
  ----------
352
426
 
353
427
  endpoint : None (padrão) ou str
354
- nome do *endpoint*
428
+ Nome do *endpoint*. Quando informado, mostra apenas a descrição
429
+ desse *endpoint*.
430
+ full : bool, default True
431
+ Quando ``endpoint`` não é informado, mostra os detalhes de todos
432
+ os *endpoints*. Use ``False`` para imprimir apenas a listagem curta
433
+ com os nomes dos *endpoints*.
355
434
 
356
435
  Returns
357
436
  -------
@@ -362,7 +441,7 @@ class BaseODataAPI:
362
441
  if endpoint:
363
442
  self.service[endpoint].describe()
364
443
  else:
365
- self.service.describe()
444
+ self.service.describe(full=full)
366
445
 
367
446
  def get_endpoint(self, endpoint: str) -> Endpoint:
368
447
  """
@@ -385,7 +464,11 @@ class BaseODataAPI:
385
464
  Se o *endpoint* fornecido é errado.
386
465
  """
387
466
  return Endpoint(
388
- self.service[endpoint], self.service.url, self.DATE_COLUMNS or None
467
+ self.service[endpoint],
468
+ self.service.url,
469
+ self.DATE_COLUMNS or None,
470
+ self.PARAMETER_FORMATTERS or None,
471
+ timeout=self._timeout,
389
472
  )
390
473
 
391
474
 
@@ -400,7 +483,7 @@ class ODataAPI(BaseODataAPI):
400
483
  não possuem implementação específica.
401
484
  """
402
485
 
403
- def __init__(self, url: str) -> None:
486
+ def __init__(self, url: str, *, timeout: RequestTimeout = None) -> None:
404
487
  """
405
488
  Parameters
406
489
  ----------
@@ -417,7 +500,8 @@ class ODataAPI(BaseODataAPI):
417
500
  - Expectativas
418
501
  - PTAX
419
502
  """
420
- self.service = ODataService(url)
503
+ self._timeout = timeout
504
+ self.service = ODataService(url, timeout=timeout)
421
505
 
422
506
 
423
507
  class Expectativas(BaseODataAPI):
@@ -499,6 +583,7 @@ class PTAX(BaseODataAPI):
499
583
  """
500
584
 
501
585
  BASE_URL = f"{OLINDA_BASE_URL}/PTAX/versao/v1/odata/"
586
+ PARAMETER_FORMATTERS = PTAX_DATE_PARAMETER_FORMATTERS
502
587
 
503
588
 
504
589
  class IFDATA(BaseODataAPI):