python-bcb 0.3.4__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/__init__.py +4 -2
- bcb/currency.py +976 -114
- bcb/exceptions.py +22 -1
- bcb/http.py +184 -0
- bcb/odata/__init__.py +3 -1
- bcb/odata/api.py +284 -33
- bcb/odata/framework.py +359 -71
- bcb/sgs/__init__.py +448 -42
- bcb/sgs/regional_economy.py +70 -44
- bcb/utils.py +2 -0
- python_bcb-0.4.0.dist-info/METADATA +225 -0
- python_bcb-0.4.0.dist-info/RECORD +14 -0
- {python_bcb-0.3.4.dist-info → python_bcb-0.4.0.dist-info}/WHEEL +1 -1
- python_bcb-0.3.4.dist-info/METADATA +0 -81
- python_bcb-0.3.4.dist-info/RECORD +0 -13
- {python_bcb-0.3.4.dist-info → python_bcb-0.4.0.dist-info}/licenses/LICENSE +0 -0
bcb/exceptions.py
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
|
|
1
4
|
class BCBError(Exception):
|
|
2
5
|
"""Base exception for all python-bcb errors."""
|
|
3
6
|
|
|
@@ -5,11 +8,29 @@ class BCBError(Exception):
|
|
|
5
8
|
class BCBAPIError(BCBError):
|
|
6
9
|
"""HTTP or API-level error from BCB."""
|
|
7
10
|
|
|
8
|
-
def __init__(self, message: str, status_code: int
|
|
11
|
+
def __init__(self, message: str, status_code: int):
|
|
9
12
|
super().__init__(message)
|
|
10
13
|
self.status_code = status_code
|
|
11
14
|
|
|
12
15
|
|
|
16
|
+
class BCBAPINotFoundError(BCBAPIError):
|
|
17
|
+
"""Raised when API returns 404 Not Found."""
|
|
18
|
+
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class BCBRateLimitError(BCBAPIError):
|
|
23
|
+
"""Raised when API returns 429 Too Many Requests (rate limit exceeded)."""
|
|
24
|
+
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class BCBAPIServerError(BCBAPIError):
|
|
29
|
+
"""Raised when API returns 5xx Server Error."""
|
|
30
|
+
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
13
34
|
class CurrencyNotFoundError(BCBError):
|
|
14
35
|
"""Raised when a requested currency symbol is not found."""
|
|
15
36
|
|
bcb/http.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""Shared HTTP client and utilities for python-bcb."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Callable, NoReturn, TypeAlias, TypeVar
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
from tenacity import (
|
|
9
|
+
retry,
|
|
10
|
+
stop_after_attempt,
|
|
11
|
+
wait_exponential,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
from bcb.exceptions import (
|
|
15
|
+
BCBAPIError,
|
|
16
|
+
BCBAPINotFoundError,
|
|
17
|
+
BCBAPIServerError,
|
|
18
|
+
BCBRateLimitError,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
# Default timeout for all HTTP requests (seconds)
|
|
22
|
+
DEFAULT_TIMEOUT = 30.0
|
|
23
|
+
|
|
24
|
+
RequestTimeout: TypeAlias = float | httpx.Timeout | None
|
|
25
|
+
|
|
26
|
+
# Shared synchronous HTTP client
|
|
27
|
+
_CLIENT = httpx.Client(
|
|
28
|
+
timeout=DEFAULT_TIMEOUT,
|
|
29
|
+
follow_redirects=True,
|
|
30
|
+
)
|
|
31
|
+
|
|
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()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
# Retry decorator for transient failures
|
|
45
|
+
# Retries on any exception (connection errors, timeouts, HTTP 5xx, etc.)
|
|
46
|
+
_retry_decorator = retry(
|
|
47
|
+
stop=stop_after_attempt(4), # 1 initial + 3 retries = 4 attempts
|
|
48
|
+
wait=wait_exponential(multiplier=1, min=1, max=10),
|
|
49
|
+
reraise=True,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def get_client() -> httpx.Client:
|
|
54
|
+
"""Get the shared synchronous HTTP client.
|
|
55
|
+
|
|
56
|
+
Returns
|
|
57
|
+
-------
|
|
58
|
+
httpx.Client
|
|
59
|
+
Shared client with connection pooling and configured timeout.
|
|
60
|
+
"""
|
|
61
|
+
return _CLIENT
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def get_async_client() -> httpx.AsyncClient:
|
|
65
|
+
"""Get the shared asynchronous HTTP client.
|
|
66
|
+
|
|
67
|
+
Returns
|
|
68
|
+
-------
|
|
69
|
+
httpx.AsyncClient
|
|
70
|
+
Shared async client with connection pooling and configured timeout.
|
|
71
|
+
"""
|
|
72
|
+
global _ASYNC_CLIENT
|
|
73
|
+
if _ASYNC_CLIENT.is_closed:
|
|
74
|
+
_ASYNC_CLIENT = _make_async_client()
|
|
75
|
+
return _ASYNC_CLIENT
|
|
76
|
+
|
|
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
|
+
|
|
84
|
+
def close_async_client() -> None:
|
|
85
|
+
"""Close the shared async client.
|
|
86
|
+
|
|
87
|
+
Call this in long-running applications before shutdown to properly
|
|
88
|
+
close HTTP connections.
|
|
89
|
+
"""
|
|
90
|
+
import asyncio
|
|
91
|
+
|
|
92
|
+
try:
|
|
93
|
+
loop = asyncio.get_running_loop()
|
|
94
|
+
except RuntimeError:
|
|
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}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
T = TypeVar("T")
|
|
108
|
+
|
|
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
|
+
|
|
171
|
+
def with_retry(func: Callable[..., T]) -> Callable[..., T]:
|
|
172
|
+
"""Decorator to add automatic retry with exponential backoff to any function.
|
|
173
|
+
|
|
174
|
+
Parameters
|
|
175
|
+
----------
|
|
176
|
+
func : Callable
|
|
177
|
+
Function to retry on failure.
|
|
178
|
+
|
|
179
|
+
Returns
|
|
180
|
+
-------
|
|
181
|
+
Callable
|
|
182
|
+
Wrapped function with automatic retry logic.
|
|
183
|
+
"""
|
|
184
|
+
return _retry_decorator(func)
|
bcb/odata/__init__.py
CHANGED
bcb/odata/api.py
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
|
-
from
|
|
2
|
-
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Callable, Literal, Optional, Union, overload
|
|
4
|
+
|
|
5
|
+
from bcb.http import RequestTimeout
|
|
6
|
+
from bcb.utils import Date
|
|
7
|
+
from bcb.odata.framework import (
|
|
3
8
|
ODataEntitySet,
|
|
9
|
+
ODataFilterExpression,
|
|
4
10
|
ODataFunctionImport,
|
|
5
11
|
ODataQuery,
|
|
6
12
|
ODataPropertyFilter,
|
|
@@ -13,12 +19,28 @@ import pandas as pd
|
|
|
13
19
|
OLINDA_BASE_URL = "https://olinda.bcb.gov.br/olinda/servico"
|
|
14
20
|
|
|
15
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
|
+
|
|
16
38
|
class EndpointMeta(type):
|
|
17
39
|
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
|
18
40
|
super().__init__(*args, **kwargs)
|
|
19
41
|
|
|
20
|
-
def __call__(self, *args: Any) -> Any:
|
|
21
|
-
obj = super().__call__(*args)
|
|
42
|
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
|
43
|
+
obj = super().__call__(*args, **kwargs)
|
|
22
44
|
entity = args[0]
|
|
23
45
|
if isinstance(entity, ODataEntitySet):
|
|
24
46
|
for name, prop in entity.entity.properties.items():
|
|
@@ -46,12 +68,39 @@ class EndpointQuery(ODataQuery):
|
|
|
46
68
|
entity: Any,
|
|
47
69
|
url: str,
|
|
48
70
|
date_columns: Optional[list[str]] = None,
|
|
71
|
+
parameter_formatters: Optional[dict[str, Callable[[Any], Any]]] = None,
|
|
72
|
+
*,
|
|
73
|
+
timeout: RequestTimeout = None,
|
|
49
74
|
) -> None:
|
|
50
|
-
super().__init__(entity, url)
|
|
75
|
+
super().__init__(entity, url, timeout=timeout)
|
|
51
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)
|
|
52
84
|
|
|
53
|
-
|
|
54
|
-
|
|
85
|
+
@overload
|
|
86
|
+
def collect(
|
|
87
|
+
self,
|
|
88
|
+
output: Literal["dataframe"] = ...,
|
|
89
|
+
*,
|
|
90
|
+
timeout: RequestTimeout = ...,
|
|
91
|
+
) -> pd.DataFrame: ...
|
|
92
|
+
|
|
93
|
+
@overload
|
|
94
|
+
def collect(
|
|
95
|
+
self, output: Literal["text"], *, timeout: RequestTimeout = ...
|
|
96
|
+
) -> str: ...
|
|
97
|
+
|
|
98
|
+
def collect(
|
|
99
|
+
self, output: str = "dataframe", *, timeout: RequestTimeout = None
|
|
100
|
+
) -> Union[pd.DataFrame, str]:
|
|
101
|
+
if output == "text":
|
|
102
|
+
return self.text(timeout=timeout)
|
|
103
|
+
raw_data = super().collect(timeout=timeout)
|
|
55
104
|
data = pd.DataFrame(raw_data["value"])
|
|
56
105
|
if not self._raw:
|
|
57
106
|
if self._date_columns:
|
|
@@ -73,6 +122,32 @@ class EndpointQuery(ODataQuery):
|
|
|
73
122
|
data[col] = pd.to_datetime(data[col])
|
|
74
123
|
return data
|
|
75
124
|
|
|
125
|
+
async def async_collect(
|
|
126
|
+
self, output: str = "dataframe", *, timeout: RequestTimeout = None
|
|
127
|
+
) -> Union[pd.DataFrame, str]:
|
|
128
|
+
"""Async version of collect(). Awaits super().async_collect() for data fetch."""
|
|
129
|
+
if output == "text":
|
|
130
|
+
return await self.async_text(timeout=timeout)
|
|
131
|
+
raw_data = await super().async_collect(timeout=timeout)
|
|
132
|
+
data = pd.DataFrame(raw_data["value"])
|
|
133
|
+
if not self._raw:
|
|
134
|
+
if self._date_columns:
|
|
135
|
+
for col in self._date_columns:
|
|
136
|
+
if col in data.columns:
|
|
137
|
+
data[col] = pd.to_datetime(data[col])
|
|
138
|
+
else:
|
|
139
|
+
endpoint_overrides = self._DATE_COLUMN_NAMES_BY_ENDPOINT.get(
|
|
140
|
+
self.entity.name, {}
|
|
141
|
+
)
|
|
142
|
+
for col in self._DATE_COLUMN_NAMES:
|
|
143
|
+
if col in endpoint_overrides:
|
|
144
|
+
data[col] = pd.to_datetime(
|
|
145
|
+
data[col], format=endpoint_overrides[col]
|
|
146
|
+
)
|
|
147
|
+
elif col in data.columns:
|
|
148
|
+
data[col] = pd.to_datetime(data[col])
|
|
149
|
+
return data
|
|
150
|
+
|
|
76
151
|
|
|
77
152
|
class Endpoint(metaclass=EndpointMeta):
|
|
78
153
|
"""
|
|
@@ -89,7 +164,13 @@ class Endpoint(metaclass=EndpointMeta):
|
|
|
89
164
|
"""
|
|
90
165
|
|
|
91
166
|
def __init__(
|
|
92
|
-
self,
|
|
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,
|
|
93
174
|
) -> None:
|
|
94
175
|
"""
|
|
95
176
|
Construtor da classe Endpoint.
|
|
@@ -108,22 +189,71 @@ class Endpoint(metaclass=EndpointMeta):
|
|
|
108
189
|
self._entity = entity
|
|
109
190
|
self._url = url
|
|
110
191
|
self._date_columns: list[str] = date_columns or []
|
|
192
|
+
self._parameter_formatters = parameter_formatters or {}
|
|
193
|
+
self._timeout = timeout
|
|
111
194
|
|
|
112
|
-
def get(
|
|
195
|
+
def get(
|
|
196
|
+
self,
|
|
197
|
+
*args: Any,
|
|
198
|
+
filter: Optional[ODataFilterExpression] = None,
|
|
199
|
+
orderby: Optional[ODataPropertyOrderBy] = None,
|
|
200
|
+
select: Optional[ODataProperty] = None,
|
|
201
|
+
limit: Optional[int] = None,
|
|
202
|
+
skip: Optional[int] = None,
|
|
203
|
+
output: str = "dataframe",
|
|
204
|
+
timeout: RequestTimeout = None,
|
|
205
|
+
verbose: bool = False,
|
|
206
|
+
**kwargs: Any,
|
|
207
|
+
) -> Union[pd.DataFrame, str]:
|
|
113
208
|
"""
|
|
114
209
|
Executa a consulta na API OData e retorna o resultado.
|
|
115
210
|
|
|
116
211
|
Parameters
|
|
117
212
|
----------
|
|
118
|
-
*args : argumentos para a consulta
|
|
119
|
-
|
|
120
|
-
|
|
213
|
+
*args : argumentos para a consulta (ODataPropertyFilter, ODataPropertyOrderBy, ODataProperty)
|
|
214
|
+
filter : ODataPropertyFilter, optional
|
|
215
|
+
Filter condition for the query
|
|
216
|
+
orderby : ODataPropertyOrderBy, optional
|
|
217
|
+
Order by condition for the query
|
|
218
|
+
select : ODataProperty, optional
|
|
219
|
+
Properties to select from the query
|
|
220
|
+
limit : int, optional
|
|
221
|
+
Limit the number of results
|
|
222
|
+
skip : int, optional
|
|
223
|
+
Skip the first N results
|
|
224
|
+
output : str, default "dataframe"
|
|
225
|
+
Output format. Use ``'text'`` to get the raw OData JSON response
|
|
226
|
+
string instead of a DataFrame.
|
|
227
|
+
verbose : bool, default False
|
|
228
|
+
Print the query before executing it
|
|
229
|
+
**kwargs : argumentos adicionais para a consulta
|
|
121
230
|
|
|
122
231
|
Returns
|
|
123
232
|
-------
|
|
124
|
-
pd.DataFrame: resultado da consulta
|
|
233
|
+
pd.DataFrame or str: resultado da consulta. Returns a DataFrame by
|
|
234
|
+
default; returns a raw JSON string when ``output='text'``.
|
|
125
235
|
"""
|
|
126
|
-
_query = EndpointQuery(
|
|
236
|
+
_query = EndpointQuery(
|
|
237
|
+
self._entity,
|
|
238
|
+
self._url,
|
|
239
|
+
self._date_columns,
|
|
240
|
+
self._parameter_formatters,
|
|
241
|
+
timeout=self._timeout,
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
# Apply explicit kwargs first
|
|
245
|
+
if filter is not None:
|
|
246
|
+
_query.filter(filter)
|
|
247
|
+
if orderby is not None:
|
|
248
|
+
_query.orderby(orderby)
|
|
249
|
+
if select is not None:
|
|
250
|
+
_query.select(select)
|
|
251
|
+
if limit is not None:
|
|
252
|
+
_query.limit(limit)
|
|
253
|
+
if skip is not None:
|
|
254
|
+
_query.skip(skip)
|
|
255
|
+
|
|
256
|
+
# Apply positional args for backwards compatibility
|
|
127
257
|
for arg in args:
|
|
128
258
|
if isinstance(arg, ODataPropertyFilter):
|
|
129
259
|
_query.filter(arg)
|
|
@@ -131,21 +261,19 @@ class Endpoint(metaclass=EndpointMeta):
|
|
|
131
261
|
_query.orderby(arg)
|
|
132
262
|
elif isinstance(arg, ODataProperty):
|
|
133
263
|
_query.select(arg)
|
|
134
|
-
|
|
264
|
+
|
|
265
|
+
# Apply any remaining kwargs as query parameters
|
|
135
266
|
for k, val in kwargs.items():
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
elif k == "skip":
|
|
139
|
-
_query.skip(val)
|
|
140
|
-
elif k == "verbose":
|
|
141
|
-
verbose = val
|
|
142
|
-
else:
|
|
143
|
-
_query.parameters(**{k: val})
|
|
267
|
+
_query.parameters(**{k: val})
|
|
268
|
+
|
|
144
269
|
_query.format("application/json")
|
|
145
270
|
|
|
146
271
|
if verbose:
|
|
147
272
|
_query.show()
|
|
148
|
-
|
|
273
|
+
if output == "text":
|
|
274
|
+
data = _query.collect(output="text", timeout=timeout)
|
|
275
|
+
else:
|
|
276
|
+
data = _query.collect(timeout=timeout)
|
|
149
277
|
_query.reset()
|
|
150
278
|
return data
|
|
151
279
|
|
|
@@ -157,7 +285,117 @@ class Endpoint(metaclass=EndpointMeta):
|
|
|
157
285
|
-------
|
|
158
286
|
bcb.odata.api.EndpointQuery
|
|
159
287
|
"""
|
|
160
|
-
return EndpointQuery(
|
|
288
|
+
return EndpointQuery(
|
|
289
|
+
self._entity,
|
|
290
|
+
self._url,
|
|
291
|
+
self._date_columns,
|
|
292
|
+
self._parameter_formatters,
|
|
293
|
+
timeout=self._timeout,
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
def async_query(self) -> EndpointQuery:
|
|
297
|
+
"""
|
|
298
|
+
Async version of query(). Returns an EndpointQuery for manual chaining with async methods.
|
|
299
|
+
|
|
300
|
+
Returns
|
|
301
|
+
-------
|
|
302
|
+
bcb.odata.api.EndpointQuery
|
|
303
|
+
Same as query(); call async_collect() on the result
|
|
304
|
+
"""
|
|
305
|
+
return EndpointQuery(
|
|
306
|
+
self._entity,
|
|
307
|
+
self._url,
|
|
308
|
+
self._date_columns,
|
|
309
|
+
self._parameter_formatters,
|
|
310
|
+
timeout=self._timeout,
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
async def async_get(
|
|
314
|
+
self,
|
|
315
|
+
*args: Any,
|
|
316
|
+
filter: Optional[ODataFilterExpression] = None,
|
|
317
|
+
orderby: Optional[ODataPropertyOrderBy] = None,
|
|
318
|
+
select: Optional[ODataProperty] = None,
|
|
319
|
+
limit: Optional[int] = None,
|
|
320
|
+
skip: Optional[int] = None,
|
|
321
|
+
output: str = "dataframe",
|
|
322
|
+
timeout: RequestTimeout = None,
|
|
323
|
+
verbose: bool = False,
|
|
324
|
+
**kwargs: Any,
|
|
325
|
+
) -> Union[pd.DataFrame, str]:
|
|
326
|
+
"""
|
|
327
|
+
Async version of get(). Executes the OData query asynchronously.
|
|
328
|
+
|
|
329
|
+
Same signature as :func:`get`, but returns a coroutine.
|
|
330
|
+
|
|
331
|
+
Parameters
|
|
332
|
+
----------
|
|
333
|
+
*args : ODataPropertyFilter, ODataPropertyOrderBy, ODataProperty
|
|
334
|
+
Positional filter/orderby/select arguments (for backwards compatibility)
|
|
335
|
+
filter : ODataPropertyFilter, optional
|
|
336
|
+
Filter condition for the query
|
|
337
|
+
orderby : ODataPropertyOrderBy, optional
|
|
338
|
+
Order by condition for the query
|
|
339
|
+
select : ODataProperty, optional
|
|
340
|
+
Properties to select from the query
|
|
341
|
+
limit : int, optional
|
|
342
|
+
Limit the number of results
|
|
343
|
+
skip : int, optional
|
|
344
|
+
Skip the first N results
|
|
345
|
+
output : str, default "dataframe"
|
|
346
|
+
Output format. Use ``'text'`` for raw JSON.
|
|
347
|
+
verbose : bool, default False
|
|
348
|
+
Print the query before executing it
|
|
349
|
+
**kwargs : argumentos adicionais para a consulta
|
|
350
|
+
|
|
351
|
+
Returns
|
|
352
|
+
-------
|
|
353
|
+
Union[pd.DataFrame, str]
|
|
354
|
+
Resultado da consulta
|
|
355
|
+
"""
|
|
356
|
+
_query = EndpointQuery(
|
|
357
|
+
self._entity,
|
|
358
|
+
self._url,
|
|
359
|
+
self._date_columns,
|
|
360
|
+
self._parameter_formatters,
|
|
361
|
+
timeout=self._timeout,
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
# Apply explicit kwargs first
|
|
365
|
+
if filter is not None:
|
|
366
|
+
_query.filter(filter)
|
|
367
|
+
if orderby is not None:
|
|
368
|
+
_query.orderby(orderby)
|
|
369
|
+
if select is not None:
|
|
370
|
+
_query.select(select)
|
|
371
|
+
if limit is not None:
|
|
372
|
+
_query.limit(limit)
|
|
373
|
+
if skip is not None:
|
|
374
|
+
_query.skip(skip)
|
|
375
|
+
|
|
376
|
+
# Apply positional args for backwards compatibility
|
|
377
|
+
for arg in args:
|
|
378
|
+
if isinstance(arg, ODataPropertyFilter):
|
|
379
|
+
_query.filter(arg)
|
|
380
|
+
elif isinstance(arg, ODataPropertyOrderBy):
|
|
381
|
+
_query.orderby(arg)
|
|
382
|
+
elif isinstance(arg, ODataProperty):
|
|
383
|
+
_query.select(arg)
|
|
384
|
+
|
|
385
|
+
# Apply any remaining kwargs as query parameters
|
|
386
|
+
for k, val in kwargs.items():
|
|
387
|
+
_query.parameters(**{k: val})
|
|
388
|
+
|
|
389
|
+
_query.format("application/json")
|
|
390
|
+
|
|
391
|
+
if verbose:
|
|
392
|
+
_query.show()
|
|
393
|
+
if output == "text":
|
|
394
|
+
data = await _query.async_collect(output="text", timeout=timeout)
|
|
395
|
+
else:
|
|
396
|
+
data = await _query.async_collect(timeout=timeout)
|
|
397
|
+
_query.reset()
|
|
398
|
+
return data
|
|
161
399
|
|
|
162
400
|
|
|
163
401
|
class BaseODataAPI:
|
|
@@ -169,14 +407,16 @@ class BaseODataAPI:
|
|
|
169
407
|
|
|
170
408
|
BASE_URL: str
|
|
171
409
|
DATE_COLUMNS: list[str] = []
|
|
410
|
+
PARAMETER_FORMATTERS: dict[str, Callable[[Any], Any]] = {}
|
|
172
411
|
|
|
173
|
-
def __init__(self) -> None:
|
|
412
|
+
def __init__(self, *, timeout: RequestTimeout = None) -> None:
|
|
174
413
|
"""
|
|
175
414
|
BaseODataAPI construtor
|
|
176
415
|
"""
|
|
177
|
-
self.
|
|
416
|
+
self._timeout = timeout
|
|
417
|
+
self.service = ODataService(self.BASE_URL, timeout=timeout)
|
|
178
418
|
|
|
179
|
-
def describe(self, endpoint: Optional[str] = None) -> None:
|
|
419
|
+
def describe(self, endpoint: Optional[str] = None, *, full: bool = True) -> None:
|
|
180
420
|
"""
|
|
181
421
|
Mostra a descrição de uma API ou de um *endpoint*
|
|
182
422
|
específico.
|
|
@@ -185,7 +425,12 @@ class BaseODataAPI:
|
|
|
185
425
|
----------
|
|
186
426
|
|
|
187
427
|
endpoint : None (padrão) ou str
|
|
188
|
-
|
|
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*.
|
|
189
434
|
|
|
190
435
|
Returns
|
|
191
436
|
-------
|
|
@@ -196,7 +441,7 @@ class BaseODataAPI:
|
|
|
196
441
|
if endpoint:
|
|
197
442
|
self.service[endpoint].describe()
|
|
198
443
|
else:
|
|
199
|
-
self.service.describe()
|
|
444
|
+
self.service.describe(full=full)
|
|
200
445
|
|
|
201
446
|
def get_endpoint(self, endpoint: str) -> Endpoint:
|
|
202
447
|
"""
|
|
@@ -219,7 +464,11 @@ class BaseODataAPI:
|
|
|
219
464
|
Se o *endpoint* fornecido é errado.
|
|
220
465
|
"""
|
|
221
466
|
return Endpoint(
|
|
222
|
-
self.service[endpoint],
|
|
467
|
+
self.service[endpoint],
|
|
468
|
+
self.service.url,
|
|
469
|
+
self.DATE_COLUMNS or None,
|
|
470
|
+
self.PARAMETER_FORMATTERS or None,
|
|
471
|
+
timeout=self._timeout,
|
|
223
472
|
)
|
|
224
473
|
|
|
225
474
|
|
|
@@ -234,7 +483,7 @@ class ODataAPI(BaseODataAPI):
|
|
|
234
483
|
não possuem implementação específica.
|
|
235
484
|
"""
|
|
236
485
|
|
|
237
|
-
def __init__(self, url: str) -> None:
|
|
486
|
+
def __init__(self, url: str, *, timeout: RequestTimeout = None) -> None:
|
|
238
487
|
"""
|
|
239
488
|
Parameters
|
|
240
489
|
----------
|
|
@@ -251,7 +500,8 @@ class ODataAPI(BaseODataAPI):
|
|
|
251
500
|
- Expectativas
|
|
252
501
|
- PTAX
|
|
253
502
|
"""
|
|
254
|
-
self.
|
|
503
|
+
self._timeout = timeout
|
|
504
|
+
self.service = ODataService(url, timeout=timeout)
|
|
255
505
|
|
|
256
506
|
|
|
257
507
|
class Expectativas(BaseODataAPI):
|
|
@@ -333,6 +583,7 @@ class PTAX(BaseODataAPI):
|
|
|
333
583
|
"""
|
|
334
584
|
|
|
335
585
|
BASE_URL = f"{OLINDA_BASE_URL}/PTAX/versao/v1/odata/"
|
|
586
|
+
PARAMETER_FORMATTERS = PTAX_DATE_PARAMETER_FORMATTERS
|
|
336
587
|
|
|
337
588
|
|
|
338
589
|
class IFDATA(BaseODataAPI):
|