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/odata/framework.py
CHANGED
|
@@ -1,14 +1,104 @@
|
|
|
1
|
-
from
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
2
4
|
import logging
|
|
5
|
+
import math
|
|
6
|
+
import threading
|
|
7
|
+
from io import BytesIO
|
|
3
8
|
from typing import Any, Optional, Union
|
|
4
|
-
from lxml import etree
|
|
5
|
-
import json
|
|
6
|
-
import httpx
|
|
7
9
|
from urllib.parse import quote
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
from lxml import etree
|
|
8
13
|
from typing_extensions import Self
|
|
9
14
|
|
|
15
|
+
from bcb.http import (
|
|
16
|
+
RequestTimeout,
|
|
17
|
+
get_async_client,
|
|
18
|
+
get_client,
|
|
19
|
+
raise_for_request_error,
|
|
20
|
+
raise_for_status,
|
|
21
|
+
timeout_kwargs,
|
|
22
|
+
)
|
|
10
23
|
from bcb.exceptions import ODataError
|
|
11
24
|
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
# Module-level metadata cache for OData services
|
|
28
|
+
# Maps service URL → ODataMetadata instance
|
|
29
|
+
_METADATA_CACHE: dict[str, "ODataMetadata"] = {}
|
|
30
|
+
_METADATA_CACHE_LOCK = threading.RLock()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _load_json_object(text: str, *, context: str) -> dict[str, Any]:
|
|
34
|
+
try:
|
|
35
|
+
data = json.loads(text)
|
|
36
|
+
except json.JSONDecodeError as ex:
|
|
37
|
+
raise ODataError(f"{context} returned invalid JSON: {ex}") from ex
|
|
38
|
+
if not isinstance(data, dict):
|
|
39
|
+
raise ODataError(f"{context} returned invalid JSON payload: expected object")
|
|
40
|
+
return data
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _required_field(data: dict[str, Any], field: str, *, context: str) -> Any:
|
|
44
|
+
try:
|
|
45
|
+
return data[field]
|
|
46
|
+
except KeyError as ex:
|
|
47
|
+
raise ODataError(f"{context} response missing required field {field!r}") from ex
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _load_xml_document(content: bytes, *, context: str) -> Any:
|
|
51
|
+
try:
|
|
52
|
+
return etree.parse(BytesIO(content))
|
|
53
|
+
except etree.XMLSyntaxError as ex:
|
|
54
|
+
raise ODataError(f"{context} returned invalid XML: {ex}") from ex
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _format_odata_string_literal(value: Any) -> str:
|
|
58
|
+
if value is None:
|
|
59
|
+
raise ODataError("Edm.String filter values cannot be None")
|
|
60
|
+
escaped = str(value).replace("'", "''")
|
|
61
|
+
return f"'{escaped}'"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _format_odata_literal(edm_type: Optional[str], value: Any) -> str:
|
|
65
|
+
if value is None:
|
|
66
|
+
raise ODataError(f"{edm_type or 'Unknown'} filter values cannot be None")
|
|
67
|
+
|
|
68
|
+
if edm_type == "Edm.Decimal":
|
|
69
|
+
try:
|
|
70
|
+
decimal_value = float(value)
|
|
71
|
+
except (TypeError, ValueError) as ex:
|
|
72
|
+
raise ODataError(f"Invalid Edm.Decimal filter value: {value!r}") from ex
|
|
73
|
+
if not math.isfinite(decimal_value):
|
|
74
|
+
raise ODataError(f"Invalid Edm.Decimal filter value: {value!r}")
|
|
75
|
+
return f"{decimal_value}"
|
|
76
|
+
|
|
77
|
+
if edm_type in ("Edm.Int16", "Edm.Int32", "Edm.Int64"):
|
|
78
|
+
try:
|
|
79
|
+
return f"{int(value)}"
|
|
80
|
+
except (TypeError, ValueError) as ex:
|
|
81
|
+
raise ODataError(f"Invalid {edm_type} filter value: {value!r}") from ex
|
|
82
|
+
|
|
83
|
+
if edm_type == "Edm.String":
|
|
84
|
+
return _format_odata_string_literal(value)
|
|
85
|
+
|
|
86
|
+
if edm_type == "Edm.Date":
|
|
87
|
+
try:
|
|
88
|
+
formatted = value.strftime("%Y-%m-%d")
|
|
89
|
+
except AttributeError as ex:
|
|
90
|
+
raise ODataError(f"Invalid Edm.Date filter value: {value!r}") from ex
|
|
91
|
+
if not isinstance(formatted, str):
|
|
92
|
+
raise ODataError(f"Invalid Edm.Date filter value: {value!r}")
|
|
93
|
+
return formatted
|
|
94
|
+
|
|
95
|
+
if edm_type == "Edm.Boolean":
|
|
96
|
+
if not isinstance(value, bool):
|
|
97
|
+
raise ODataError(f"Invalid Edm.Boolean filter value: {value!r}")
|
|
98
|
+
return str(value).lower()
|
|
99
|
+
|
|
100
|
+
raise ODataError(f"Unsupported OData filter literal type: {edm_type or 'Unknown'}")
|
|
101
|
+
|
|
12
102
|
|
|
13
103
|
# Edm.Boolean
|
|
14
104
|
# Edm.Byte
|
|
@@ -78,12 +168,10 @@ class ODataEntitySet(metaclass=ODataEntitySetMeta):
|
|
|
78
168
|
props = ", ".join(
|
|
79
169
|
[f"{prop.name}<{prop.ftype}>" for prop in self.entity.properties.values()]
|
|
80
170
|
)
|
|
81
|
-
print(
|
|
82
|
-
f"""
|
|
171
|
+
print(f"""
|
|
83
172
|
EntitySet (Endpoint): {self.name}
|
|
84
173
|
EntityType: {self.entity_type}
|
|
85
|
-
Properties: {props}"""
|
|
86
|
-
)
|
|
174
|
+
Properties: {props}""")
|
|
87
175
|
|
|
88
176
|
def __repr__(self) -> str:
|
|
89
177
|
return f"<EntitySet {self.name}>"
|
|
@@ -166,23 +254,25 @@ class ODataPropertyOrderBy:
|
|
|
166
254
|
return f"<{str(self)}>"
|
|
167
255
|
|
|
168
256
|
|
|
169
|
-
class
|
|
170
|
-
def __init__(self, obj: "ODataProperty", oth: Any, operator: str) -> None:
|
|
171
|
-
self.obj = obj
|
|
172
|
-
self.other = oth
|
|
173
|
-
self.operator = operator
|
|
174
|
-
|
|
257
|
+
class ODataFilterExpression:
|
|
175
258
|
def statement(self) -> str:
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
return
|
|
259
|
+
raise NotImplementedError
|
|
260
|
+
|
|
261
|
+
def __and__(self, other: object) -> Any:
|
|
262
|
+
if not isinstance(other, ODataFilterExpression):
|
|
263
|
+
return NotImplemented
|
|
264
|
+
return ODataCombinedFilter(self, other, "and")
|
|
265
|
+
|
|
266
|
+
def __or__(self, other: object) -> Any:
|
|
267
|
+
if not isinstance(other, ODataFilterExpression):
|
|
268
|
+
return NotImplemented
|
|
269
|
+
return ODataCombinedFilter(self, other, "or")
|
|
270
|
+
|
|
271
|
+
def __bool__(self) -> bool:
|
|
272
|
+
raise TypeError(
|
|
273
|
+
"OData filters cannot be evaluated as booleans. "
|
|
274
|
+
"Use & for AND and | for OR, with parentheses around comparisons."
|
|
275
|
+
)
|
|
186
276
|
|
|
187
277
|
def __str__(self) -> str:
|
|
188
278
|
return self.statement()
|
|
@@ -191,6 +281,32 @@ class ODataPropertyFilter:
|
|
|
191
281
|
return f"<filter: {str(self)}>"
|
|
192
282
|
|
|
193
283
|
|
|
284
|
+
class ODataCombinedFilter(ODataFilterExpression):
|
|
285
|
+
def __init__(
|
|
286
|
+
self,
|
|
287
|
+
left: ODataFilterExpression,
|
|
288
|
+
right: ODataFilterExpression,
|
|
289
|
+
operator: str,
|
|
290
|
+
) -> None:
|
|
291
|
+
self.left = left
|
|
292
|
+
self.right = right
|
|
293
|
+
self.operator = operator
|
|
294
|
+
|
|
295
|
+
def statement(self) -> str:
|
|
296
|
+
return f"({self.left.statement()} {self.operator} {self.right.statement()})"
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
class ODataPropertyFilter(ODataFilterExpression):
|
|
300
|
+
def __init__(self, obj: "ODataProperty", oth: Any, operator: str) -> None:
|
|
301
|
+
self.obj = obj
|
|
302
|
+
self.other = oth
|
|
303
|
+
self.operator = operator
|
|
304
|
+
|
|
305
|
+
def statement(self) -> str:
|
|
306
|
+
literal = _format_odata_literal(self.obj.type, self.other)
|
|
307
|
+
return f"{self.obj.name} {self.operator} {literal}"
|
|
308
|
+
|
|
309
|
+
|
|
194
310
|
class ODataProperty:
|
|
195
311
|
def __init__(self, **kwargs: Any) -> None:
|
|
196
312
|
self.data: dict[str, Any] = kwargs
|
|
@@ -237,7 +353,7 @@ class ODataFunction:
|
|
|
237
353
|
self.name: str = kwargs["Name"]
|
|
238
354
|
self.parameters: list[ODataParameter] = kwargs["parameters"]
|
|
239
355
|
self.return_type: str = kwargs["return_type"]
|
|
240
|
-
self.fullname: str = f
|
|
356
|
+
self.fullname: str = f"{kwargs['namespace']}.{self.name}"
|
|
241
357
|
|
|
242
358
|
def __repr__(self) -> str:
|
|
243
359
|
return f"<Function {self.name}>"
|
|
@@ -261,21 +377,49 @@ class ODataMetadata:
|
|
|
261
377
|
"edmx": "http://docs.oasis-open.org/odata/ns/edmx",
|
|
262
378
|
}
|
|
263
379
|
|
|
264
|
-
def __init__(self, url: str) -> None:
|
|
380
|
+
def __init__(self, url: str, *, timeout: RequestTimeout = None) -> None:
|
|
265
381
|
self.url = url
|
|
266
|
-
self.
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
382
|
+
self._timeout = timeout
|
|
383
|
+
self._load_document(timeout=timeout)
|
|
384
|
+
try:
|
|
385
|
+
_xpath = "edmx:DataServices/edm:Schema"
|
|
386
|
+
schemas = self.doc.xpath(_xpath, namespaces=self.namespaces)
|
|
387
|
+
if not schemas:
|
|
388
|
+
raise ODataError(f"OData metadata {self.url} missing schema")
|
|
389
|
+
schema = schemas[0]
|
|
390
|
+
self.namespace = schema.attrib["Namespace"]
|
|
391
|
+
self._used_elements: list[str] = []
|
|
392
|
+
self._parse_entities(schema)
|
|
393
|
+
self._parse_entity_sets(schema)
|
|
394
|
+
self._parse_functions(schema)
|
|
395
|
+
self._parse_function_imports(schema)
|
|
396
|
+
except ODataError:
|
|
397
|
+
raise
|
|
398
|
+
except (KeyError, IndexError, TypeError) as ex:
|
|
399
|
+
raise ODataError(
|
|
400
|
+
f"OData metadata {self.url} has invalid structure: {ex}"
|
|
401
|
+
) from ex
|
|
402
|
+
|
|
403
|
+
def _load_document(self, *, timeout: RequestTimeout = None) -> None:
|
|
404
|
+
logger.debug(f"Fetching OData metadata from {self.url}")
|
|
405
|
+
try:
|
|
406
|
+
res = get_client().get(self.url, **timeout_kwargs(timeout))
|
|
407
|
+
except httpx.HTTPError as ex:
|
|
408
|
+
raise_for_request_error(
|
|
409
|
+
ex, context=f"OData metadata {self.url}", error_cls=ODataError
|
|
410
|
+
)
|
|
411
|
+
logger.debug(
|
|
412
|
+
f"OData metadata response: status={res.status_code}, length={len(res.content)}"
|
|
413
|
+
)
|
|
414
|
+
raise_for_status(
|
|
415
|
+
res,
|
|
416
|
+
context=f"OData metadata {self.url}",
|
|
417
|
+
error_cls=ODataError,
|
|
418
|
+
not_found_cls=ODataError,
|
|
419
|
+
rate_limit_cls=ODataError,
|
|
420
|
+
server_error_cls=ODataError,
|
|
421
|
+
)
|
|
422
|
+
self.doc = _load_xml_document(res.content, context=f"OData metadata {self.url}")
|
|
279
423
|
|
|
280
424
|
def _parse_entity(self, entity_element: Any, namespace: str) -> ODataEntity:
|
|
281
425
|
name = entity_element.attrib["Name"]
|
|
@@ -356,15 +500,60 @@ class ODataMetadata:
|
|
|
356
500
|
|
|
357
501
|
|
|
358
502
|
class ODataService:
|
|
359
|
-
|
|
503
|
+
"""OData service client.
|
|
504
|
+
|
|
505
|
+
Parameters
|
|
506
|
+
----------
|
|
507
|
+
url : str
|
|
508
|
+
OData service root URL
|
|
509
|
+
"""
|
|
510
|
+
|
|
511
|
+
def __init__(self, url: str, *, timeout: RequestTimeout = None) -> None:
|
|
360
512
|
self.url = url
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
513
|
+
self._timeout = timeout
|
|
514
|
+
try:
|
|
515
|
+
res = get_client().get(self.url, **timeout_kwargs(timeout))
|
|
516
|
+
except httpx.HTTPError as ex:
|
|
517
|
+
raise_for_request_error(
|
|
518
|
+
ex, context=f"OData service {self.url}", error_cls=ODataError
|
|
519
|
+
)
|
|
520
|
+
raise_for_status(
|
|
521
|
+
res,
|
|
522
|
+
context=f"OData service {self.url}",
|
|
523
|
+
error_cls=ODataError,
|
|
524
|
+
not_found_cls=ODataError,
|
|
525
|
+
rate_limit_cls=ODataError,
|
|
526
|
+
server_error_cls=ODataError,
|
|
527
|
+
)
|
|
528
|
+
context = f"OData service {self.url}"
|
|
529
|
+
self.api_data = _load_json_object(res.text, context=context)
|
|
530
|
+
value = _required_field(self.api_data, "value", context=context)
|
|
531
|
+
if not isinstance(value, list):
|
|
532
|
+
raise ODataError("OData service response field 'value' must be a list")
|
|
533
|
+
endpoints = []
|
|
534
|
+
for endpoint in value:
|
|
535
|
+
if not isinstance(endpoint, dict):
|
|
536
|
+
raise ODataError(
|
|
537
|
+
"OData service response field 'value' must contain objects"
|
|
538
|
+
)
|
|
539
|
+
endpoints.append(ODataEndPoint(**endpoint))
|
|
540
|
+
self.endpoints = endpoints
|
|
541
|
+
odata_context = _required_field(
|
|
542
|
+
self.api_data, "@odata.context", context=context
|
|
543
|
+
)
|
|
544
|
+
if not isinstance(odata_context, str):
|
|
545
|
+
raise ODataError(
|
|
546
|
+
"OData service response field '@odata.context' must be a string"
|
|
547
|
+
)
|
|
548
|
+
self._odata_context_url = odata_context
|
|
549
|
+
|
|
550
|
+
# Use cached metadata if available, otherwise create and cache new one
|
|
551
|
+
with _METADATA_CACHE_LOCK:
|
|
552
|
+
if self._odata_context_url in _METADATA_CACHE:
|
|
553
|
+
self.metadata = _METADATA_CACHE[self._odata_context_url]
|
|
554
|
+
else:
|
|
555
|
+
self.metadata = ODataMetadata(self._odata_context_url, timeout=timeout)
|
|
556
|
+
_METADATA_CACHE[self._odata_context_url] = self.metadata
|
|
368
557
|
|
|
369
558
|
def __getitem__(self, item: str) -> Union[ODataEntitySet, ODataFunctionImport]:
|
|
370
559
|
es = self.entity_sets.get(item)
|
|
@@ -389,43 +578,65 @@ class ODataService:
|
|
|
389
578
|
def entity_sets(self) -> dict[str, ODataEntitySet]:
|
|
390
579
|
return self.metadata.entity_sets
|
|
391
580
|
|
|
392
|
-
def
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
if
|
|
397
|
-
|
|
398
|
-
|
|
581
|
+
def _standalone_entity_sets(self) -> list[ODataEntitySet]:
|
|
582
|
+
return [
|
|
583
|
+
entity_set
|
|
584
|
+
for name, entity_set in self.entity_sets.items()
|
|
585
|
+
if f"{self.metadata.namespace}.{name}" not in self.metadata._used_elements
|
|
586
|
+
]
|
|
587
|
+
|
|
588
|
+
def describe(self, *, full: bool = False) -> None:
|
|
589
|
+
entity_sets = self._standalone_entity_sets()
|
|
590
|
+
function_imports = list(self.function_imports.values())
|
|
591
|
+
|
|
592
|
+
if full:
|
|
593
|
+
if entity_sets:
|
|
594
|
+
print("EntitySets:")
|
|
595
|
+
for entity_set in entity_sets:
|
|
596
|
+
entity_set.describe()
|
|
597
|
+
if function_imports:
|
|
598
|
+
print("FunctionImports:")
|
|
599
|
+
for function_import in function_imports:
|
|
600
|
+
function_import.describe()
|
|
601
|
+
return
|
|
602
|
+
|
|
603
|
+
if entity_sets:
|
|
399
604
|
print("EntitySets:")
|
|
400
|
-
for
|
|
401
|
-
print(" ",
|
|
402
|
-
if
|
|
605
|
+
for entity_set in entity_sets:
|
|
606
|
+
print(" ", entity_set.name)
|
|
607
|
+
if function_imports:
|
|
403
608
|
print("FunctionImports:")
|
|
404
|
-
for
|
|
405
|
-
print(" ",
|
|
609
|
+
for function_import in function_imports:
|
|
610
|
+
print(" ", function_import.name)
|
|
406
611
|
|
|
407
612
|
def query(
|
|
408
613
|
self, entity_set: Union[ODataEntitySet, ODataFunctionImport]
|
|
409
614
|
) -> "ODataQuery":
|
|
410
|
-
return ODataQuery(entity_set, self.url)
|
|
615
|
+
return ODataQuery(entity_set, self.url, timeout=self._timeout)
|
|
411
616
|
|
|
412
617
|
|
|
413
618
|
class ODataQuery:
|
|
414
619
|
def __init__(
|
|
415
|
-
self,
|
|
620
|
+
self,
|
|
621
|
+
entity: Union[ODataEntitySet, ODataFunctionImport],
|
|
622
|
+
url: str,
|
|
623
|
+
*,
|
|
624
|
+
timeout: RequestTimeout = None,
|
|
416
625
|
) -> None:
|
|
417
626
|
self.entity = entity
|
|
418
627
|
self.base_url = url
|
|
628
|
+
self._timeout = timeout
|
|
419
629
|
self._params: dict[str, Any] = {}
|
|
420
630
|
self.function_parameters: dict[str, Any] = {}
|
|
421
|
-
self._filter: list[
|
|
631
|
+
self._filter: list[ODataFilterExpression] = []
|
|
422
632
|
self._select: list[ODataProperty] = []
|
|
423
633
|
self._orderby: list[ODataPropertyOrderBy] = []
|
|
424
634
|
self._raw = False
|
|
425
635
|
self.is_function = isinstance(entity, ODataFunctionImport)
|
|
426
636
|
if self.is_function:
|
|
427
637
|
self.function_parameters = {
|
|
428
|
-
(p.name or ""): None
|
|
638
|
+
(p.name or ""): None
|
|
639
|
+
for p in self.entity.function.parameters # type: ignore[union-attr]
|
|
429
640
|
}
|
|
430
641
|
|
|
431
642
|
def odata_url(self) -> str:
|
|
@@ -449,7 +660,10 @@ class ODataQuery:
|
|
|
449
660
|
raise ODataError(f"Unknown parameter: {arg}")
|
|
450
661
|
return self
|
|
451
662
|
|
|
452
|
-
def
|
|
663
|
+
def _format_parameter(self, parameter: ODataParameter, value: Any) -> str:
|
|
664
|
+
return parameter.format(value)
|
|
665
|
+
|
|
666
|
+
def filter(self, *args: ODataFilterExpression) -> Self:
|
|
453
667
|
if len(args):
|
|
454
668
|
self._filter.extend(args)
|
|
455
669
|
return self
|
|
@@ -499,24 +713,97 @@ class ODataQuery:
|
|
|
499
713
|
self._orderby = []
|
|
500
714
|
self._params = {}
|
|
501
715
|
|
|
502
|
-
def
|
|
503
|
-
|
|
716
|
+
def _resolve_timeout(self, timeout: RequestTimeout) -> RequestTimeout:
|
|
717
|
+
if timeout is None:
|
|
718
|
+
return self._timeout
|
|
719
|
+
return timeout
|
|
720
|
+
|
|
721
|
+
def collect(self, *, timeout: RequestTimeout = None) -> Any:
|
|
722
|
+
url = self.odata_url()
|
|
723
|
+
data = _load_json_object(
|
|
724
|
+
self.text(timeout=timeout), context=f"OData query {url}"
|
|
725
|
+
)
|
|
726
|
+
_required_field(data, "value", context=f"OData query {url}")
|
|
727
|
+
return data
|
|
728
|
+
|
|
729
|
+
async def async_text(self, *, timeout: RequestTimeout = None) -> str:
|
|
730
|
+
"""Async version of text(). Fetches OData response using shared client."""
|
|
731
|
+
params = self._build_parameters()
|
|
732
|
+
if self.is_function and len(self.function_parameters):
|
|
733
|
+
for p in self.entity.function.parameters: # type: ignore[union-attr]
|
|
734
|
+
val = self.function_parameters[p.name or ""]
|
|
735
|
+
if p.required and val is None:
|
|
736
|
+
raise ODataError("Parameter not set: " + (p.name or ""))
|
|
737
|
+
params["@" + (p.name or "")] = self._format_parameter(p, val)
|
|
738
|
+
qs = "&".join([f"{quote(k)}={quote(str(v))}" for k, v in params.items()])
|
|
739
|
+
headers = {"OData-Version": "4.0", "OData-MaxVersion": "4.0"}
|
|
740
|
+
url = self.odata_url()
|
|
741
|
+
try:
|
|
742
|
+
res = await get_async_client().get(
|
|
743
|
+
url + "?" + qs,
|
|
744
|
+
headers=headers,
|
|
745
|
+
**timeout_kwargs(self._resolve_timeout(timeout)),
|
|
746
|
+
)
|
|
747
|
+
except httpx.HTTPError as ex:
|
|
748
|
+
raise_for_request_error(
|
|
749
|
+
ex, context=f"OData query {url}", error_cls=ODataError
|
|
750
|
+
)
|
|
751
|
+
raise_for_status(
|
|
752
|
+
res,
|
|
753
|
+
context=f"OData query {url}",
|
|
754
|
+
error_cls=ODataError,
|
|
755
|
+
not_found_cls=ODataError,
|
|
756
|
+
rate_limit_cls=ODataError,
|
|
757
|
+
server_error_cls=ODataError,
|
|
758
|
+
)
|
|
759
|
+
return res.text
|
|
760
|
+
|
|
761
|
+
async def async_collect(self, *, timeout: RequestTimeout = None) -> Any:
|
|
762
|
+
"""Async version of collect(). Awaits async_text() and parses JSON."""
|
|
763
|
+
url = self.odata_url()
|
|
764
|
+
data = _load_json_object(
|
|
765
|
+
await self.async_text(timeout=timeout), context=f"OData query {url}"
|
|
766
|
+
)
|
|
767
|
+
_required_field(data, "value", context=f"OData query {url}")
|
|
768
|
+
return data
|
|
504
769
|
|
|
505
|
-
def text(self) -> str:
|
|
770
|
+
def text(self, *, timeout: RequestTimeout = None) -> str:
|
|
506
771
|
params = self._build_parameters()
|
|
507
772
|
if self.is_function and len(self.function_parameters):
|
|
508
773
|
for p in self.entity.function.parameters: # type: ignore[union-attr]
|
|
509
774
|
val = self.function_parameters[p.name or ""]
|
|
510
775
|
if p.required and val is None:
|
|
511
776
|
raise ODataError("Parameter not set: " + (p.name or ""))
|
|
512
|
-
params["@" + (p.name or "")] =
|
|
777
|
+
params["@" + (p.name or "")] = self._format_parameter(p, val)
|
|
513
778
|
qs = "&".join([f"{quote(k)}={quote(str(v))}" for k, v in params.items()])
|
|
514
779
|
headers = {"OData-Version": "4.0", "OData-MaxVersion": "4.0"}
|
|
515
|
-
|
|
780
|
+
url = self.odata_url()
|
|
781
|
+
logger.debug(f"Fetching OData query from {url}")
|
|
782
|
+
try:
|
|
783
|
+
res = get_client().get(
|
|
784
|
+
url + "?" + qs,
|
|
785
|
+
headers=headers,
|
|
786
|
+
**timeout_kwargs(self._resolve_timeout(timeout)),
|
|
787
|
+
)
|
|
788
|
+
except httpx.HTTPError as ex:
|
|
789
|
+
raise_for_request_error(
|
|
790
|
+
ex, context=f"OData query {url}", error_cls=ODataError
|
|
791
|
+
)
|
|
792
|
+
logger.debug(
|
|
793
|
+
f"OData query response: status={res.status_code}, length={len(res.text)}"
|
|
794
|
+
)
|
|
795
|
+
raise_for_status(
|
|
796
|
+
res,
|
|
797
|
+
context=f"OData query {url}",
|
|
798
|
+
error_cls=ODataError,
|
|
799
|
+
not_found_cls=ODataError,
|
|
800
|
+
rate_limit_cls=ODataError,
|
|
801
|
+
server_error_cls=ODataError,
|
|
802
|
+
)
|
|
516
803
|
return res.text
|
|
517
804
|
|
|
518
805
|
def show(self) -> None:
|
|
519
|
-
print(
|
|
806
|
+
print("URL:")
|
|
520
807
|
print(f" {self.odata_url()}")
|
|
521
808
|
if self.is_function and len(self.function_parameters):
|
|
522
809
|
print("Function Parameters:")
|
|
@@ -538,7 +825,8 @@ class ODataQuery:
|
|
|
538
825
|
print("Return:", names_str)
|
|
539
826
|
else:
|
|
540
827
|
names = [
|
|
541
|
-
f"{p.name}<{p.ftype}>"
|
|
828
|
+
f"{p.name}<{p.ftype}>"
|
|
829
|
+
for p in self.entity.entity.properties.values() # type: ignore[union-attr]
|
|
542
830
|
]
|
|
543
831
|
names_str = ", ".join(names)
|
|
544
832
|
print("Return:", names_str)
|