python-bcb 0.3.4__py3-none-any.whl → 0.3.6__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/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 | None = None):
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,98 @@
1
+ """Shared HTTP client and utilities for python-bcb."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Callable, TypeVar
6
+
7
+ import httpx
8
+ from tenacity import (
9
+ retry,
10
+ stop_after_attempt,
11
+ wait_exponential,
12
+ )
13
+
14
+ # Default timeout for all HTTP requests (seconds)
15
+ DEFAULT_TIMEOUT = 30.0
16
+
17
+ # Shared synchronous HTTP client
18
+ _CLIENT = httpx.Client(
19
+ timeout=DEFAULT_TIMEOUT,
20
+ follow_redirects=True,
21
+ )
22
+
23
+ # Shared asynchronous HTTP client (for future async API)
24
+ _ASYNC_CLIENT = httpx.AsyncClient(
25
+ timeout=DEFAULT_TIMEOUT,
26
+ follow_redirects=True,
27
+ )
28
+
29
+
30
+ # Retry decorator for transient failures
31
+ # Retries on any exception (connection errors, timeouts, HTTP 5xx, etc.)
32
+ _retry_decorator = retry(
33
+ stop=stop_after_attempt(4), # 1 initial + 3 retries = 4 attempts
34
+ wait=wait_exponential(multiplier=1, min=1, max=10),
35
+ reraise=True,
36
+ )
37
+
38
+
39
+ def get_client() -> httpx.Client:
40
+ """Get the shared synchronous HTTP client.
41
+
42
+ Returns
43
+ -------
44
+ httpx.Client
45
+ Shared client with connection pooling and configured timeout.
46
+ """
47
+ return _CLIENT
48
+
49
+
50
+ def get_async_client() -> httpx.AsyncClient:
51
+ """Get the shared asynchronous HTTP client.
52
+
53
+ Returns
54
+ -------
55
+ httpx.AsyncClient
56
+ Shared async client with connection pooling and configured timeout.
57
+ """
58
+ return _ASYNC_CLIENT
59
+
60
+
61
+ def close_async_client() -> None:
62
+ """Close the shared async client.
63
+
64
+ Call this in long-running applications before shutdown to properly
65
+ close HTTP connections.
66
+ """
67
+ import asyncio
68
+
69
+ 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())
77
+ except RuntimeError:
78
+ # No event loop, create one
79
+ asyncio.run(_ASYNC_CLIENT.aclose())
80
+
81
+
82
+ T = TypeVar("T")
83
+
84
+
85
+ def with_retry(func: Callable[..., T]) -> Callable[..., T]:
86
+ """Decorator to add automatic retry with exponential backoff to any function.
87
+
88
+ Parameters
89
+ ----------
90
+ func : Callable
91
+ Function to retry on failure.
92
+
93
+ Returns
94
+ -------
95
+ Callable
96
+ Wrapped function with automatic retry logic.
97
+ """
98
+ return _retry_decorator(func)
bcb/odata/__init__.py CHANGED
@@ -1,4 +1,6 @@
1
- from .api import (
1
+ from __future__ import annotations
2
+
3
+ from bcb.odata.api import (
2
4
  ODataAPI,
3
5
  Expectativas,
4
6
  PTAX,
bcb/odata/api.py CHANGED
@@ -1,5 +1,8 @@
1
- from typing import Any, Optional
2
- from .framework import (
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Literal, Optional, Union, overload
4
+
5
+ from bcb.odata.framework import (
3
6
  ODataEntitySet,
4
7
  ODataFunctionImport,
5
8
  ODataQuery,
@@ -50,7 +53,15 @@ class EndpointQuery(ODataQuery):
50
53
  super().__init__(entity, url)
51
54
  self._date_columns: list[str] = date_columns or []
52
55
 
53
- def collect(self) -> pd.DataFrame:
56
+ @overload
57
+ def collect(self, output: Literal["dataframe"] = ...) -> pd.DataFrame: ...
58
+
59
+ @overload
60
+ def collect(self, output: Literal["text"]) -> str: ...
61
+
62
+ def collect(self, output: str = "dataframe") -> Union[pd.DataFrame, str]:
63
+ if output == "text":
64
+ return self.text()
54
65
  raw_data = super().collect()
55
66
  data = pd.DataFrame(raw_data["value"])
56
67
  if not self._raw:
@@ -73,6 +84,32 @@ class EndpointQuery(ODataQuery):
73
84
  data[col] = pd.to_datetime(data[col])
74
85
  return data
75
86
 
87
+ async def async_collect(
88
+ self, output: str = "dataframe"
89
+ ) -> Union[pd.DataFrame, str]:
90
+ """Async version of collect(). Awaits super().async_collect() for data fetch."""
91
+ if output == "text":
92
+ return await self.async_text()
93
+ raw_data = await super().async_collect()
94
+ data = pd.DataFrame(raw_data["value"])
95
+ if not self._raw:
96
+ if self._date_columns:
97
+ for col in self._date_columns:
98
+ if col in data.columns:
99
+ data[col] = pd.to_datetime(data[col])
100
+ else:
101
+ endpoint_overrides = self._DATE_COLUMN_NAMES_BY_ENDPOINT.get(
102
+ self.entity.name, {}
103
+ )
104
+ for col in self._DATE_COLUMN_NAMES:
105
+ if col in endpoint_overrides:
106
+ data[col] = pd.to_datetime(
107
+ data[col], format=endpoint_overrides[col]
108
+ )
109
+ elif col in data.columns:
110
+ data[col] = pd.to_datetime(data[col])
111
+ return data
112
+
76
113
 
77
114
  class Endpoint(metaclass=EndpointMeta):
78
115
  """
@@ -109,21 +146,61 @@ class Endpoint(metaclass=EndpointMeta):
109
146
  self._url = url
110
147
  self._date_columns: list[str] = date_columns or []
111
148
 
112
- def get(self, *args: Any, **kwargs: Any) -> pd.DataFrame:
149
+ def get(
150
+ self,
151
+ *args: Any,
152
+ filter: Optional[ODataPropertyFilter] = None,
153
+ orderby: Optional[ODataPropertyOrderBy] = None,
154
+ select: Optional[ODataProperty] = None,
155
+ limit: Optional[int] = None,
156
+ skip: Optional[int] = None,
157
+ output: str = "dataframe",
158
+ verbose: bool = False,
159
+ **kwargs: Any,
160
+ ) -> Union[pd.DataFrame, str]:
113
161
  """
114
162
  Executa a consulta na API OData e retorna o resultado.
115
163
 
116
164
  Parameters
117
165
  ----------
118
- *args : argumentos para a consulta
119
-
120
- **kwargs : argumentos para a consulta
166
+ *args : argumentos para a consulta (ODataPropertyFilter, ODataPropertyOrderBy, ODataProperty)
167
+ filter : ODataPropertyFilter, optional
168
+ Filter condition for the query
169
+ orderby : ODataPropertyOrderBy, optional
170
+ Order by condition for the query
171
+ select : ODataProperty, optional
172
+ Properties to select from the query
173
+ limit : int, optional
174
+ Limit the number of results
175
+ skip : int, optional
176
+ Skip the first N results
177
+ output : str, default "dataframe"
178
+ Output format. Use ``'text'`` to get the raw OData JSON response
179
+ string instead of a DataFrame.
180
+ verbose : bool, default False
181
+ Print the query before executing it
182
+ **kwargs : argumentos adicionais para a consulta
121
183
 
122
184
  Returns
123
185
  -------
124
- pd.DataFrame: resultado da consulta
186
+ pd.DataFrame or str: resultado da consulta. Returns a DataFrame by
187
+ default; returns a raw JSON string when ``output='text'``.
125
188
  """
126
189
  _query = EndpointQuery(self._entity, self._url, self._date_columns)
190
+
191
+ # Apply explicit kwargs first
192
+ if filter is not None:
193
+ _query.filter(filter)
194
+ if orderby is not None:
195
+ _query.orderby(orderby)
196
+ if select is not None:
197
+ _query.select(select)
198
+ if limit is not None:
199
+ _query.limit(limit)
200
+ if skip is not None:
201
+ _query.skip(skip)
202
+
203
+ # Apply positional args for backwards compatibility
127
204
  for arg in args:
128
205
  if isinstance(arg, ODataPropertyFilter):
129
206
  _query.filter(arg)
@@ -131,21 +208,19 @@ class Endpoint(metaclass=EndpointMeta):
131
208
  _query.orderby(arg)
132
209
  elif isinstance(arg, ODataProperty):
133
210
  _query.select(arg)
134
- verbose = False
211
+
212
+ # Apply any remaining kwargs as query parameters
135
213
  for k, val in kwargs.items():
136
- if k == "limit":
137
- _query.limit(val)
138
- elif k == "skip":
139
- _query.skip(val)
140
- elif k == "verbose":
141
- verbose = val
142
- else:
143
- _query.parameters(**{k: val})
214
+ _query.parameters(**{k: val})
215
+
144
216
  _query.format("application/json")
145
217
 
146
218
  if verbose:
147
219
  _query.show()
148
- data = _query.collect()
220
+ if output == "text":
221
+ data = _query.collect(output="text")
222
+ else:
223
+ data = _query.collect()
149
224
  _query.reset()
150
225
  return data
151
226
 
@@ -159,6 +234,97 @@ class Endpoint(metaclass=EndpointMeta):
159
234
  """
160
235
  return EndpointQuery(self._entity, self._url, self._date_columns)
161
236
 
237
+ def async_query(self) -> EndpointQuery:
238
+ """
239
+ Async version of query(). Returns an EndpointQuery for manual chaining with async methods.
240
+
241
+ Returns
242
+ -------
243
+ bcb.odata.api.EndpointQuery
244
+ Same as query(); call async_collect() on the result
245
+ """
246
+ return EndpointQuery(self._entity, self._url, self._date_columns)
247
+
248
+ async def async_get(
249
+ self,
250
+ *args: Any,
251
+ filter: Optional[ODataPropertyFilter] = None,
252
+ orderby: Optional[ODataPropertyOrderBy] = None,
253
+ select: Optional[ODataProperty] = None,
254
+ limit: Optional[int] = None,
255
+ skip: Optional[int] = None,
256
+ output: str = "dataframe",
257
+ verbose: bool = False,
258
+ **kwargs: Any,
259
+ ) -> Union[pd.DataFrame, str]:
260
+ """
261
+ Async version of get(). Executes the OData query asynchronously.
262
+
263
+ Same signature as :func:`get`, but returns a coroutine.
264
+
265
+ Parameters
266
+ ----------
267
+ *args : ODataPropertyFilter, ODataPropertyOrderBy, ODataProperty
268
+ Positional filter/orderby/select arguments (for backwards compatibility)
269
+ filter : ODataPropertyFilter, optional
270
+ Filter condition for the query
271
+ orderby : ODataPropertyOrderBy, optional
272
+ Order by condition for the query
273
+ select : ODataProperty, optional
274
+ Properties to select from the query
275
+ limit : int, optional
276
+ Limit the number of results
277
+ skip : int, optional
278
+ Skip the first N results
279
+ output : str, default "dataframe"
280
+ Output format. Use ``'text'`` for raw JSON.
281
+ verbose : bool, default False
282
+ Print the query before executing it
283
+ **kwargs : argumentos adicionais para a consulta
284
+
285
+ Returns
286
+ -------
287
+ Union[pd.DataFrame, str]
288
+ Resultado da consulta
289
+ """
290
+ _query = EndpointQuery(self._entity, self._url, self._date_columns)
291
+
292
+ # Apply explicit kwargs first
293
+ if filter is not None:
294
+ _query.filter(filter)
295
+ if orderby is not None:
296
+ _query.orderby(orderby)
297
+ if select is not None:
298
+ _query.select(select)
299
+ if limit is not None:
300
+ _query.limit(limit)
301
+ if skip is not None:
302
+ _query.skip(skip)
303
+
304
+ # Apply positional args for backwards compatibility
305
+ for arg in args:
306
+ if isinstance(arg, ODataPropertyFilter):
307
+ _query.filter(arg)
308
+ elif isinstance(arg, ODataPropertyOrderBy):
309
+ _query.orderby(arg)
310
+ elif isinstance(arg, ODataProperty):
311
+ _query.select(arg)
312
+
313
+ # Apply any remaining kwargs as query parameters
314
+ for k, val in kwargs.items():
315
+ _query.parameters(**{k: val})
316
+
317
+ _query.format("application/json")
318
+
319
+ if verbose:
320
+ _query.show()
321
+ if output == "text":
322
+ data = await _query.async_collect(output="text")
323
+ else:
324
+ data = await _query.async_collect()
325
+ _query.reset()
326
+ return data
327
+
162
328
 
163
329
  class BaseODataAPI:
164
330
  """
bcb/odata/framework.py CHANGED
@@ -1,14 +1,24 @@
1
- from io import BytesIO
1
+ from __future__ import annotations
2
+
2
3
  import logging
4
+ import threading
5
+ from io import BytesIO
3
6
  from typing import Any, Optional, Union
7
+
4
8
  from lxml import etree
5
9
  import json
6
- import httpx
7
10
  from urllib.parse import quote
8
11
  from typing_extensions import Self
9
12
 
13
+ from bcb.http import _CLIENT, _ASYNC_CLIENT
10
14
  from bcb.exceptions import ODataError
11
15
 
16
+ logger = logging.getLogger(__name__)
17
+
18
+ # Module-level metadata cache for OData services
19
+ # Maps service URL → ODataMetadata instance
20
+ _METADATA_CACHE: dict[str, "ODataMetadata"] = {}
21
+ _METADATA_CACHE_LOCK = threading.RLock()
12
22
 
13
23
  # Edm.Boolean
14
24
  # Edm.Byte
@@ -78,12 +88,10 @@ class ODataEntitySet(metaclass=ODataEntitySetMeta):
78
88
  props = ", ".join(
79
89
  [f"{prop.name}<{prop.ftype}>" for prop in self.entity.properties.values()]
80
90
  )
81
- print(
82
- f"""
91
+ print(f"""
83
92
  EntitySet (Endpoint): {self.name}
84
93
  EntityType: {self.entity_type}
85
- Properties: {props}"""
86
- )
94
+ Properties: {props}""")
87
95
 
88
96
  def __repr__(self) -> str:
89
97
  return f"<EntitySet {self.name}>"
@@ -237,7 +245,7 @@ class ODataFunction:
237
245
  self.name: str = kwargs["Name"]
238
246
  self.parameters: list[ODataParameter] = kwargs["parameters"]
239
247
  self.return_type: str = kwargs["return_type"]
240
- self.fullname: str = f'{kwargs["namespace"]}.{self.name}'
248
+ self.fullname: str = f"{kwargs['namespace']}.{self.name}"
241
249
 
242
250
  def __repr__(self) -> str:
243
251
  return f"<Function {self.name}>"
@@ -274,7 +282,11 @@ class ODataMetadata:
274
282
  self._parse_function_imports(schema)
275
283
 
276
284
  def _load_document(self) -> None:
277
- res = httpx.get(self.url, timeout=60.0)
285
+ logger.debug(f"Fetching OData metadata from {self.url}")
286
+ res = _CLIENT.get(self.url)
287
+ logger.debug(
288
+ f"OData metadata response: status={res.status_code}, length={len(res.content)}"
289
+ )
278
290
  self.doc = etree.parse(BytesIO(res.content))
279
291
 
280
292
  def _parse_entity(self, entity_element: Any, namespace: str) -> ODataEntity:
@@ -356,15 +368,30 @@ class ODataMetadata:
356
368
 
357
369
 
358
370
  class ODataService:
371
+ """OData service client.
372
+
373
+ Parameters
374
+ ----------
375
+ url : str
376
+ OData service root URL
377
+ """
378
+
359
379
  def __init__(self, url: str) -> None:
360
380
  self.url = url
361
- res = httpx.get(self.url, timeout=60.0)
381
+ res = _CLIENT.get(self.url)
362
382
  self.api_data: dict[str, Any] = json.loads(res.text)
363
383
  self.endpoints: list[ODataEndPoint] = [
364
384
  ODataEndPoint(**x) for x in self.api_data["value"]
365
385
  ]
366
386
  self._odata_context_url: str = self.api_data["@odata.context"]
367
- self.metadata = ODataMetadata(self._odata_context_url)
387
+
388
+ # Use cached metadata if available, otherwise create and cache new one
389
+ with _METADATA_CACHE_LOCK:
390
+ if self._odata_context_url in _METADATA_CACHE:
391
+ self.metadata = _METADATA_CACHE[self._odata_context_url]
392
+ else:
393
+ self.metadata = ODataMetadata(self._odata_context_url)
394
+ _METADATA_CACHE[self._odata_context_url] = self.metadata
368
395
 
369
396
  def __getitem__(self, item: str) -> Union[ODataEntitySet, ODataFunctionImport]:
370
397
  es = self.entity_sets.get(item)
@@ -425,7 +452,8 @@ class ODataQuery:
425
452
  self.is_function = isinstance(entity, ODataFunctionImport)
426
453
  if self.is_function:
427
454
  self.function_parameters = {
428
- (p.name or ""): None for p in self.entity.function.parameters # type: ignore[union-attr]
455
+ (p.name or ""): None
456
+ for p in self.entity.function.parameters # type: ignore[union-attr]
429
457
  }
430
458
 
431
459
  def odata_url(self) -> str:
@@ -502,6 +530,24 @@ class ODataQuery:
502
530
  def collect(self) -> Any:
503
531
  return json.loads(self.text())
504
532
 
533
+ async def async_text(self) -> str:
534
+ """Async version of text(). Fetches OData response using _ASYNC_CLIENT."""
535
+ params = self._build_parameters()
536
+ if self.is_function and len(self.function_parameters):
537
+ for p in self.entity.function.parameters: # type: ignore[union-attr]
538
+ val = self.function_parameters[p.name or ""]
539
+ if p.required and val is None:
540
+ raise ODataError("Parameter not set: " + (p.name or ""))
541
+ params["@" + (p.name or "")] = p.format(val)
542
+ qs = "&".join([f"{quote(k)}={quote(str(v))}" for k, v in params.items()])
543
+ headers = {"OData-Version": "4.0", "OData-MaxVersion": "4.0"}
544
+ res = await _ASYNC_CLIENT.get(self.odata_url() + "?" + qs, headers=headers)
545
+ return res.text
546
+
547
+ async def async_collect(self) -> Any:
548
+ """Async version of collect(). Awaits async_text() and parses JSON."""
549
+ return json.loads(await self.async_text())
550
+
505
551
  def text(self) -> str:
506
552
  params = self._build_parameters()
507
553
  if self.is_function and len(self.function_parameters):
@@ -512,11 +558,16 @@ class ODataQuery:
512
558
  params["@" + (p.name or "")] = p.format(val)
513
559
  qs = "&".join([f"{quote(k)}={quote(str(v))}" for k, v in params.items()])
514
560
  headers = {"OData-Version": "4.0", "OData-MaxVersion": "4.0"}
515
- res = httpx.get(self.odata_url() + "?" + qs, headers=headers, timeout=60.0)
561
+ url = self.odata_url()
562
+ logger.debug(f"Fetching OData query from {url}")
563
+ res = _CLIENT.get(url + "?" + qs, headers=headers)
564
+ logger.debug(
565
+ f"OData query response: status={res.status_code}, length={len(res.text)}"
566
+ )
516
567
  return res.text
517
568
 
518
569
  def show(self) -> None:
519
- print(f"URL:")
570
+ print("URL:")
520
571
  print(f" {self.odata_url()}")
521
572
  if self.is_function and len(self.function_parameters):
522
573
  print("Function Parameters:")
@@ -538,7 +589,8 @@ class ODataQuery:
538
589
  print("Return:", names_str)
539
590
  else:
540
591
  names = [
541
- f"{p.name}<{p.ftype}>" for p in self.entity.entity.properties.values() # type: ignore[union-attr]
592
+ f"{p.name}<{p.ftype}>"
593
+ for p in self.entity.entity.properties.values() # type: ignore[union-attr]
542
594
  ]
543
595
  names_str = ", ".join(names)
544
596
  print("Return:", names_str)